home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / gnu / amiga / gasldsrc.lha / binutils / ld.c
C/C++ Source or Header  |  1992-04-19  |  197KB  |  7,125 lines

  1. /* Linker `ld' for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Richard Stallman with some help from Eric Albert.
  19.    Set, indirect, and warning symbol features added by Randy Smith.
  20.    Support for generation of Amiga load files added by Markus Wild. */
  21.  
  22. #ifdef MCH_AMIGA
  23. #ifndef STANDARD_SEARCH_DIRS
  24. #define STANDARD_SEARCH_DIRS "local:lib","local:gcc-lib","gcc:lib"
  25. #endif
  26. #endif
  27.  
  28. #include <ar.h>
  29. #include <stdio.h>
  30. #include <sys/types.h>
  31. #include <sys/stat.h>
  32. #include <sys/file.h>
  33. #ifndef USG
  34. #include <sys/time.h>
  35. #include <sys/resource.h>
  36. #endif
  37. #ifndef sony_news
  38. #include <fcntl.h>
  39. #endif
  40.  
  41. #if !defined(A_OUT) && !defined(MACH_O)
  42. #define A_OUT
  43. #endif
  44.  
  45. #ifdef A_OUT
  46. #ifdef COFF_ENCAPSULATE
  47. #include "a.out.encap.h"
  48. #else
  49. #include <a.out.h>
  50. #endif
  51. #endif
  52.  
  53. #ifdef MCH_AMIGA
  54. #define HUNK_INSTEAD_OF_A_OUT
  55. int number_of_code_hunk,
  56.     number_of_data_hunk,
  57.     number_of_bss_hunk,
  58.     number_of_debug_hunk,
  59.     current_hunk = 0,
  60.     offset_of_debug_hunk,
  61.     amiga_symbols_only,
  62.     databss_together = 0,
  63.     numdatadata_relocs = 0,
  64.     output_datadata_relocs = 0,
  65.     datadata_relocs_offset = 0;
  66. #define LONGSIZE(l) ((((l) + 3) & ~3) >> 2)
  67. /* this is the private format of the debug-hunk: */
  68.    struct debug_hunk {
  69.      unsigned long  id;  /* Filesystem-imposed: HUNK_DEBUG (0x3f1) */
  70.      unsigned long  len; /* "" : length in longs -> LONGSIZE(real_lenght) */
  71.      /* the following part is somehow a truncated exec-struct: */
  72.      unsigned long  magic; /* should be ZMAGIC (just for fun:-)), to be recognised
  73.                 * by the other tools as this special frame */
  74.      unsigned long  syms;  /* size of symbol-table */
  75.      unsigned long  strs;  /* size of string table */
  76.      /* here follows the actual data */
  77.    } dh;
  78. #endif
  79.  
  80. #ifdef MACH_O
  81. #ifndef A_OUT
  82. #include <nlist.h>
  83. #include <reloc.h>
  84. #endif
  85. #ifndef N_TEXT
  86. #define N_TEXT 0x04
  87. #define N_DATA 0x06
  88. #define N_BSS 0x08
  89. #endif
  90. #include <sys/loader.h>
  91. #endif
  92.  
  93. #ifndef N_SET_MAGIC
  94. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  95. #endif
  96.  
  97. /* If compiled with GNU C, use the built-in alloca */
  98. #ifdef __GNUC__
  99. # define alloca __builtin_alloca
  100. #else
  101. # if defined(sun) && defined(sparc)
  102. #  include "alloca.h"
  103. # else
  104. char *alloca ();
  105. # endif
  106. #endif
  107.  
  108. #include "getopt.h"
  109.  
  110. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  111.  
  112. #include "stab.h"
  113. #define CORE_ADDR unsigned long    /* For symseg.h */
  114. #include "symseg.h"
  115.  
  116. #ifdef USG
  117. #include <string.h>
  118. #else
  119. #include <strings.h>
  120. #endif
  121.  
  122. /* Determine whether we should attempt to handle (minimally)
  123.    N_BINCL and N_EINCL.  */
  124.  
  125. #if defined (__GNU_STAB__) || defined (N_BINCL)
  126. #define HAVE_SUN_STABS
  127. #endif
  128.  
  129. #define min(a,b) ((a) < (b) ? (a) : (b))
  130.  
  131. /* Macro to control the number of undefined references printed */
  132. #define MAX_UREFS_PRINTED    10
  133.  
  134. /* Size of a page; obtained from the operating system.  */
  135.  
  136. int page_size;
  137.  
  138. /* Name this program was invoked by.  */
  139.  
  140. char *progname;
  141.  
  142. /* System dependencies */
  143.  
  144. /* Define this if names etext, edata and end should not start with `_'.  */
  145. /* #define nounderscore 1 */
  146.  
  147. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  148.    whose native format is different.  */
  149. /* #define NON_NATIVE */
  150.  
  151. /* Define this to specify the default executable format.  */
  152.  
  153. #ifdef hpux
  154. #define DEFAULT_OUTPUT_STYLE OUTPUT_READONLY_TEXT
  155. #endif
  156.  
  157. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  158.  
  159. #ifndef N_TXTADDR
  160. #if defined(vax) || defined(sony_news) || defined(hp300) || defined(pyr)
  161. #define N_TXTADDR(X) 0
  162. #endif
  163. #ifdef is68k
  164. #define N_TXTADDR(x)  (sizeof (struct exec))
  165. #endif
  166. #ifdef sequent
  167. #define    N_TXTADDR(x) (N_ADDRADJ(x))
  168. #endif
  169. #ifdef NeXT
  170. #define N_TXTADDR(X) ((X).a_magic == ZMAGIC ? page_size : 0)
  171. #endif
  172. #endif
  173.  
  174. #ifndef N_DATADDR
  175. #if defined(vax) || defined(sony_news) || defined(hp300) || defined(pyr)
  176. #define N_DATADDR(x) \
  177.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  178.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  179. #endif
  180. #ifdef is68k
  181. #define SEGMENT_SIZE 0x20000
  182. #define N_DATADDR(x) \
  183.     (((x).a_magic==Omagic)? (N_TXTADDR(x)+(x).a_text) \
  184.      : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  185. #endif
  186. #ifdef sequent
  187. #define N_DATADDR(x) \
  188.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  189.     : (page_size+(((x).a_text-1) & ~(page_size-1))))
  190. #endif
  191. #ifdef NeXT
  192. #define N_DATADDR(X) \
  193.     (((X).a_magic==ZMAGIC)?(N_TXTADDR(X)+(X).a_text+0xFFFF)&~0xFFFF \
  194.      :N_TXTADDR(X)+(X).a_text)
  195. #endif
  196. #endif
  197.  
  198. /* The "address" of the data segment in a relocatable file.
  199.    The text address of a relocatable file is always
  200.    considered to be zero (instead of the value of N_TXTADDR, which
  201.    is what the address is in an executable), so we need to subtract
  202.    N_TXTADDR from N_DATADDR to get the "address" for the input file.  */
  203. #define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
  204.  
  205. /* Define how to initialize system-dependent header fields.  */
  206. #ifdef sun
  207. #ifdef sparc
  208. #define INITIALIZE_HEADER \
  209.   {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  210. #endif /* sparc.  */
  211. #if defined(mc68000)
  212. /* Set the machine type according to the machine type of the .o files.
  213.    If they are all sun2 (68010), then the type of the executable is sun2.
  214.    If any is sun3 (68020), then the type of the executable is sun3.
  215.    This is consistent with the Sun loader and more useful than having
  216.    it depend on which machine you are on when you run ld.  */
  217. static int sun_machtype = M_68010;
  218. #define INITIALIZE_HEADER outheader.a_machtype = sun_machtype
  219. #define READ_HEADER_HOOK(machtype) \
  220.   if (machtype == M_68020)           \
  221.     {                     \
  222.       sun_machtype = M_68020;         \
  223.     }
  224. #endif /* mc68000.  */
  225. #endif /* Sun.  */
  226.  
  227. #ifdef amigados
  228. /* same trick as with sun[23] */
  229. /* Set the machine type according to the machine type of the .o files.
  230.    If they are all sun2 (68010), then the type of the executable is sun2.
  231.    If any is sun3 (68020), then the type of the executable is sun3.
  232.    This is consistent with the Sun loader and more useful than having
  233.    it depend on which machine you are on when you run ld.  */
  234. static int amiga_machtype = MID_SUN010;
  235. #define INITIALIZE_HEADER outheader.a_machtype = amiga_machtype
  236. #define READ_HEADER_HOOK(machtype) \
  237.   if (machtype == MID_SUN020)        \
  238.     {                     \
  239.       amiga_machtype = MID_SUN020;   \
  240.     }
  241. #endif
  242.  
  243. #ifdef ALTOS
  244. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_68020)
  245. #endif
  246. #ifdef is68k
  247. #ifdef M_68020
  248. /* ISI rel 4.0D doesn't use it, and rel 3.05 doesn't have an
  249.    a_machtype field and so won't recognize the magic number.  To keep
  250.    binary compatibility for now, just ignore it */
  251. #define INITIALIZE_HEADER outheader.a_machtype = 0;
  252. #endif
  253. #endif
  254. #ifdef hpux
  255. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, HP9000S200_ID)
  256. #endif
  257. #if defined(i386) && !defined(sequent)
  258. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_386)
  259. #endif /* Sequent symmetry.  */
  260. #if defined(hp300)
  261. #define INITIALIZE_HEADER outheader.a_mid = MID_HP300
  262. #endif /* hp300.  */
  263. #ifdef pyr
  264. #define INITIALIZE_HEADER outheader.a_machid = PYR90X
  265. #endif /* Pyramid.  */
  266.  
  267. #ifdef is68k
  268. /* This enables code to take care of an ugly hack in the ISI OS.
  269.    If a symbol beings with _$, then the object file is included only
  270.    if the rest of the symbol name has been referenced. */
  271. #define DOLLAR_KLUDGE
  272. #endif
  273.  
  274. /* Values for 3rd argument to lseek().  */
  275. #ifndef L_SET
  276. #define L_SET 0
  277. #endif
  278. /* This is called L_INCR in BSD, but SEEK_CUR in POSIX.  */
  279. #ifndef SEEK_CUR
  280. #define SEEK_CUR 1
  281. #endif
  282.  
  283. /*
  284.  * Ok.  Following are the relocation information macros.  If your
  285.  * system cannot use the default set (below), you must define all of these:
  286.  
  287.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  288.  * of structure that is stored in the relocation info section of your
  289.  * a.out files.  Often this is defined in the a.out.h for your system.
  290.  *
  291.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  292.  * <whatever> to be relocated.  *Must be an lvalue*.
  293.  *
  294.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  295.  * external symbol (1), or was it fully resolved upon entering the
  296.  * loader (0) in which case some combination of the value in memory
  297.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  298.  * what the value of the relocation actually was.  *Must be an lvalue*.
  299.  *
  300.  *   RELOC_TYPE (rval): For a non-external relocation, this is the
  301.  * segment to relocate for.  *Must be an lvalue.*
  302.  *
  303.  *   RELOC_SYMBOL (rval): For an external relocation, this is the
  304.  * index of its symbol in the symbol table.  *Must be an lvalue*.
  305.  *
  306.  *   RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
  307.  * relocation value output here should be added to memory; 0, if the
  308.  * section of memory described should simply be set to the relocation
  309.  * value.
  310.  *
  311.  *   RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
  312.  * present in the memory location to be relocated is *added*
  313.  * to the relocation value, to produce the final result.
  314.  * Otherwise, the relocation value is stored in the memory location
  315.  * and the value previously found there is ignored.
  316.  * By default, this is always 1.
  317.  *
  318.  *   RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
  319.  * present in the memory location to be relocated is *subtracted*
  320.  * from the relocation value, to produce the final result.
  321.  * By default, this is always 0.
  322.  *
  323.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  324.  * an extra value to be added to the relocation value based on the
  325.  * individual relocation entry.  *Must be an lvalue if defined*.
  326.  *
  327.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  328.  * pc relative.
  329.  *
  330.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  331.  * final relocation value before putting it where it belongs.
  332.  *
  333.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  334.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  335.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  336.  * do everything in terms of the bit operators below), but having this
  337.  * macro could end up producing better code on machines without fancy
  338.  * bit twiddling.  Also, it's easier to understand/code big/little
  339.  * endian distinctions with this macro.
  340.  *
  341.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  342.  * object described in RELOC_TARGET_SIZE in which the relocation value
  343.  * will go.
  344.  *
  345.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  346.  * with the bits of the relocation value.  It may be assumed by the
  347.  * code that the relocation value will fit into this many bits.  This
  348.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  349.  *
  350.  *
  351.  *        Things I haven't implemented
  352.  *        ----------------------------
  353.  *
  354.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  355.  *
  356.  *    Pc relative relocation for External references.
  357.  *
  358.  *
  359.  */
  360.  
  361. #if defined(sun) && defined(sparc)
  362. /* Sparc (Sun 4) macros */
  363. #undef relocation_info
  364. #define relocation_info                    reloc_info_sparc
  365. #define RELOC_ADDRESS(r)        ((r)->r_address)
  366. #define RELOC_EXTERN_P(r)               ((r)->r_extern)
  367. #define RELOC_TYPE(r)                   ((r)->r_index)
  368. #define RELOC_SYMBOL(r)                 ((r)->r_index)
  369. #define RELOC_MEMORY_SUB_P(r)        0
  370. #define RELOC_MEMORY_ADD_P(r)           0
  371. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)
  372. #define RELOC_PCREL_P(r)             \
  373.         ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
  374. #define RELOC_VALUE_RIGHTSHIFT(r)       (reloc_target_rightshift[(r)->r_type])
  375. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(r)->r_type])
  376. #define RELOC_TARGET_BITPOS(r)          0
  377. #define RELOC_TARGET_BITSIZE(r)         (reloc_target_bitsize[(r)->r_type])
  378.  
  379. /* Note that these are very dependent on the order of the enums in
  380.    enum reloc_type (in a.out.h); if they change the following must be
  381.    changed */
  382. /* Also note that the last few may be incorrect; I have no information */
  383. static int reloc_target_rightshift[] = {
  384.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  385. };
  386. static int reloc_target_size[] = {
  387.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  388. };
  389. static int reloc_target_bitsize[] = {
  390.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  391. };
  392.  
  393. #define    MAX_ALIGNMENT    (sizeof (double))
  394. #endif
  395.  
  396. #ifdef sequent
  397. #define RELOC_ADDRESS(r)        ((r)->r_address)
  398. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  399. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  400. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  401. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  402. #define RELOC_MEMORY_ADD_P(r)    1
  403. #undef RELOC_ADD_EXTRA
  404. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  405. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  406. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  407. #define RELOC_TARGET_BITPOS(r)    0
  408. #define RELOC_TARGET_BITSIZE(r)    32
  409. #endif
  410.  
  411. /* Default macros */
  412. #ifndef RELOC_ADDRESS
  413. #define RELOC_ADDRESS(r)        ((r)->r_address)
  414. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  415. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  416. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  417. #define RELOC_MEMORY_SUB_P(r)    0
  418. #define RELOC_MEMORY_ADD_P(r)    1
  419. #undef RELOC_ADD_EXTRA
  420. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  421. #define RELOC_BASEREL_P(r)        ((r)->r_baserel)
  422. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  423. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  424. #define RELOC_TARGET_BITPOS(r)    0
  425. #define RELOC_TARGET_BITSIZE(r)    32
  426. #endif
  427.  
  428. #ifndef MAX_ALIGNMENT
  429. #define    MAX_ALIGNMENT    (sizeof (int))
  430. #endif
  431.  
  432. #ifdef nounderscore
  433. #define LPREFIX '.'
  434. #else
  435. #define LPREFIX 'L'
  436. #endif
  437.  
  438.  
  439. /* Special global symbol types understood by GNU LD.  */
  440.  
  441. /* The following type indicates the definition of a symbol as being
  442.    an indirect reference to another symbol.  The other symbol
  443.    appears as an undefined reference, immediately following this symbol.
  444.  
  445.    Indirection is asymmetrical.  The other symbol's value will be used
  446.    to satisfy requests for the indirect symbol, but not vice versa.
  447.    If the other symbol does not have a definition, libraries will
  448.    be searched to find a definition.
  449.  
  450.    So, for example, the following two lines placed in an assembler
  451.    input file would result in an object file which would direct gnu ld
  452.    to resolve all references to symbol "foo" as references to symbol
  453.    "bar".
  454.  
  455.     .stabs "_foo",11,0,0,0
  456.     .stabs "_bar",1,0,0,0
  457.  
  458.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  459.  
  460. #ifndef N_INDR
  461. #define N_INDR 0xa
  462. #endif
  463.  
  464. /* The following symbols refer to set elements.  These are expected
  465.    only in input to the loader; they should not appear in loader
  466.    output (unless relocatable output is requested).  To be recognized
  467.    by the loader, the input symbols must have their N_EXT bit set.
  468.    All the N_SET[ATDB] symbols with the same name form one set.  The
  469.    loader collects all of these elements at load time and outputs a
  470.    vector for each name.
  471.    Space (an array of 32 bit words) is allocated for the set in the
  472.    data section, and the n_value field of each set element value is
  473.    stored into one word of the array.
  474.    The first word of the array is the length of the set (number of
  475.    elements).  The last word of the vector is set to zero for possible
  476.    use by incremental loaders.  The array is ordered by the linkage
  477.    order; the first symbols which the linker encounters will be first
  478.    in the array.
  479.  
  480.    In C syntax this looks like:
  481.  
  482.     struct set_vector {
  483.       unsigned int length;
  484.       unsigned int vector[length];
  485.       unsigned int always_zero;
  486.     };
  487.  
  488.    Before being placed into the array, each element is relocated
  489.    according to its type.  This allows the loader to create an array
  490.    of pointers to objects automatically.  N_SETA type symbols will not
  491.    be relocated.
  492.  
  493.    The address of the set is made into an N_SETV symbol
  494.    whose name is the same as the name of the set.
  495.    This symbol acts like a N_DATA global symbol
  496.    in that it can satisfy undefined external references.
  497.  
  498.    For the purposes of determining whether or not to load in a library
  499.    file, set element definitions are not considered "real
  500.    definitions"; they will not cause the loading of a library
  501.    member.
  502.  
  503.    If relocatable output is requested, none of this processing is
  504.    done.  The symbols are simply relocated and passed through to the
  505.    output file.
  506.  
  507.    So, for example, the following three lines of assembler code
  508.    (whether in one file or scattered between several different ones)
  509.    will produce a three element vector (total length is five words;
  510.    see above), referenced by the symbol "_xyzzy", which will have the
  511.    addresses of the routines _init1, _init2, and _init3.
  512.  
  513.    *NOTE*: If symbolic addresses are used in the n_value field of the
  514.    defining .stabs, those symbols must be defined in the same file as
  515.    that containing the .stabs.
  516.  
  517.     .stabs "_xyzzy",23,0,0,_init1
  518.     .stabs "_xyzzy",23,0,0,_init2
  519.     .stabs "_xyzzy",23,0,0,_init3
  520.  
  521.    Note that (23 == (N_SETT | N_EXT)).  */
  522.  
  523. #ifndef N_SETA
  524. #define    N_SETA    0x14        /* Absolute set element symbol */
  525. #endif                /* This is input to LD, in a .o file.  */
  526.  
  527. #ifndef N_SETT
  528. #define    N_SETT    0x16        /* Text set element symbol */
  529. #endif                /* This is input to LD, in a .o file.  */
  530.  
  531. #ifndef N_SETD
  532. #define    N_SETD    0x18        /* Data set element symbol */
  533. #endif                /* This is input to LD, in a .o file.  */
  534.  
  535. #ifndef N_SETB
  536. #define    N_SETB    0x1A        /* Bss set element symbol */
  537. #endif                /* This is input to LD, in a .o file.  */
  538.  
  539. /* Macros dealing with the set element symbols defined in a.out.h */
  540. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  541. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  542.  
  543. #ifndef N_SETV
  544. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  545. #endif                /* This is output from LD.  */
  546.  
  547. /* If a this type of symbol is encountered, its name is a warning
  548.    message to print each time the symbol referenced by the next symbol
  549.    table entry is referenced.
  550.  
  551.    This feature may be used to allow backwards compatibility with
  552.    certain functions (eg. gets) but to discourage programmers from
  553.    their use.
  554.  
  555.    So if, for example, you wanted to have ld print a warning whenever
  556.    the function "gets" was used in their C program, you would add the
  557.    following to the assembler file in which gets is defined:
  558.  
  559.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  560.     .stabs "_gets",1,0,0,0
  561.  
  562.    These .stabs do not necessarily have to be in the same file as the
  563.    gets function, they simply must exist somewhere in the compilation.  */
  564.  
  565. #ifndef N_WARNING
  566. #define N_WARNING 0x1E        /* Warning message to print if symbol
  567.                    included */
  568. #endif                /* This is input to ld */
  569.  
  570. #ifndef __GNU_STAB__
  571.  
  572. /* Line number for the data section.  This is to be used to describe
  573.    the source location of a variable declaration.  */
  574. #ifndef N_DSLINE
  575. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  576. #endif
  577.  
  578. /* Line number for the bss section.  This is to be used to describe
  579.    the source location of a variable declaration.  */
  580. #ifndef N_BSLINE
  581. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  582. #endif
  583.  
  584. #endif /* not __GNU_STAB__ */
  585.  
  586. /* Symbol table */
  587.  
  588. /* Global symbol data is recorded in these structures,
  589.    one for each global symbol.
  590.    They are found via hashing in 'symtab', which points to a vector of buckets.
  591.    Each bucket is a chain of these structures through the link field.  */
  592.  
  593. typedef
  594.   struct glosym
  595.     {
  596.       /* Pointer to next symbol in this symbol's hash bucket.  */
  597.       struct glosym *link;
  598.       /* Name of this symbol.  */
  599.       char *name;
  600.       /* Value of this symbol as a global symbol.  */
  601.       long value;
  602.       /* Chain of external 'nlist's in files for this symbol, both defs
  603.      and refs.  */
  604.       struct nlist *refs;
  605.       /* Any warning message that might be associated with this symbol
  606.          from an N_WARNING symbol encountered. */
  607.       char *warning;
  608.       /* Nonzero means definitions of this symbol as common have been seen,
  609.      and the value here is the largest size specified by any of them.  */
  610.       int max_common_size;
  611.       /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
  612.      symbol table to be written, with the first global sym given index 0.*/
  613.       int def_count;
  614.       /* Nonzero means a definition of this global symbol is known to exist.
  615.      Library members should not be loaded on its account.  */
  616.       char defined;
  617.       /* Nonzero means a reference to this global symbol has been seen
  618.      in a file that is surely being loaded.
  619.      A value higher than 1 is the n_type code for the symbol's
  620.      definition.  */
  621.       char referenced;
  622.       /* A count of the number of undefined references printed for a
  623.      specific symbol.  If a symbol is unresolved at the end of
  624.      digest_symbols (and the loading run is supposed to produce
  625.      relocatable output) do_file_warnings keeps track of how many
  626.      unresolved reference error messages have been printed for
  627.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  628.      messages stop. */
  629.       unsigned char undef_refs;
  630.       /* 1 means that this symbol has multiple definitions.  2 means
  631.          that it has multiple definitions, and some of them are set
  632.      elements, one of which has been printed out already.  */
  633.       unsigned char multiply_defined;
  634.       /* Nonzero means print a message at all refs or defs of this symbol */
  635.       char trace;
  636.     }
  637.   symbol;
  638.  
  639. /* Demangler for C++.  */
  640. extern char *cplus_demangle ();
  641.  
  642. /* Demangler function to use.  We unconditionally enable the C++ demangler
  643.    because we assume any name it successfully demangles was probably produced
  644.    by the C++ compiler.  Enabling it only if -lg++ was specified seems too
  645.    much of a kludge.  */
  646. char *(*demangler)() = cplus_demangle;
  647.  
  648. /* Number of buckets in symbol hash table */
  649. #define    TABSIZE    1009
  650.  
  651. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  652. symbol *symtab[TABSIZE];
  653.  
  654. /* Number of symbols in symbol hash table. */
  655. int num_hash_tab_syms = 0;
  656.  
  657. /* Count the number of nlist entries that are for local symbols.
  658.    This count and the three following counts
  659.    are incremented as as symbols are entered in the symbol table.  */
  660. int local_sym_count;
  661.  
  662. /* Count number of nlist entries that are for local symbols
  663.    whose names don't start with L. */
  664. int non_L_local_sym_count;
  665.  
  666. /* Count the number of nlist entries for debugger info.  */
  667. int debugger_sym_count;
  668.  
  669. /* Count the number of global symbols referenced and not defined.  */
  670. int undefined_global_sym_count;
  671.  
  672. /* Count the number of global symbols multiply defined.  */
  673. int multiple_def_count;
  674.  
  675. /* Count the number of defined global symbols.
  676.    Each symbol is counted only once
  677.    regardless of how many different nlist entries refer to it,
  678.    since the output file will need only one nlist entry for it.
  679.    This count is computed by `digest_symbols';
  680.    it is undefined while symbols are being loaded. */
  681. int defined_global_sym_count;
  682.  
  683. /* Count the number of symbols defined through common declarations.
  684.    This count is kept in symdef_library, linear_library, and
  685.    enter_global_ref.  It is incremented when the defined flag is set
  686.    in a symbol because of a common definition, and decremented when
  687.    the symbol is defined "for real" (ie. by something besides a common
  688.    definition).  */
  689. int common_defined_global_count;
  690.  
  691. /* Count the number of set element type symbols and the number of
  692.    separate vectors which these symbols will fit into.  See the
  693.    GNU a.out.h for more info.
  694.    This count is computed by 'enter_file_symbols' */
  695. int set_symbol_count;
  696. int set_vector_count;
  697.  
  698. /* Define a linked list of strings which define symbols which should
  699.    be treated as set elements even though they aren't.  Any symbol
  700.    with a prefix matching one of these should be treated as a set
  701.    element.
  702.  
  703.    This is to make up for deficiencies in many assemblers which aren't
  704.    willing to pass any stabs through to the loader which they don't
  705.    understand.  */
  706. struct string_list_element {
  707.   char *str;
  708.   struct string_list_element *next;
  709. };
  710.  
  711. struct string_list_element *set_element_prefixes;
  712.  
  713. /* Count the number of definitions done indirectly (ie. done relative
  714.    to the value of some other symbol. */
  715. int global_indirect_count;
  716.  
  717. /* Count the number of warning symbols encountered. */
  718. int warning_count;
  719.  
  720. /* Total number of symbols to be written in the output file.
  721.    Computed by digest_symbols from the variables above.  */
  722. int nsyms;
  723.  
  724.  
  725. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  726.    -e sets this.  */
  727. symbol *entry_symbol;
  728.  
  729. /* These can be NULL if we don't actually have such a symbol.  */
  730. symbol *edata_symbol;   /* the symbol _edata */
  731. symbol *etext_symbol;   /* the symbol _etext */
  732. symbol *end_symbol;    /* the symbol _end */
  733. /* We also need __{edata,etext,end} so that they can safely
  734.    be used from an ANSI library.  */
  735. symbol *edata_symbol_alt;
  736. symbol *etext_symbol_alt;
  737. symbol *end_symbol_alt;
  738.  
  739. #ifdef amigados
  740. symbol *sdata_symbol;    /* the symbol __sdata */
  741. symbol *text_size_symbol;
  742. symbol *data_size_symbol;
  743. symbol *bss_size_symbol;
  744. symbol *datadata_reloc_symbol = 0;
  745. #endif
  746.  
  747. /* Kinds of files potentially understood by the linker. */
  748.  
  749. enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
  750.  
  751. /* Each input file, and each library member ("subfile") being loaded,
  752.    has a `file_entry' structure for it.
  753.  
  754.    For files specified by command args, these are contained in the vector
  755.    which `file_table' points to.
  756.  
  757.    For library members, they are dynamically allocated,
  758.    and chained through the `chain' field.
  759.    The chain is found in the `subfiles' field of the `file_entry'.
  760.    The `file_entry' objects for the members have `superfile' fields pointing
  761.    to the one for the library.  */
  762.  
  763. struct file_entry {
  764.   /* Name of this file.  */
  765.   char *filename;
  766.  
  767.   /* What kind of file this is. */
  768.   enum file_type file_type;
  769.  
  770.   /* Name to use for the symbol giving address of text start */
  771.   /* Usually the same as filename, but for a file spec'd with -l
  772.      this is the -l switch itself rather than the filename.  */
  773.   char *local_sym_name;
  774.  
  775.   /* Describe the layout of the contents of the file.  */
  776.  
  777.   /* The text section. */
  778.   unsigned long int orig_text_address;
  779.   unsigned long int text_size;
  780.   long int text_offset;
  781.  
  782.   /* Text relocation. */
  783.   unsigned long int text_reloc_size;
  784.   long int text_reloc_offset;
  785.  
  786.   /* The data section. */
  787.   unsigned long int orig_data_address;
  788.   unsigned long int data_size;
  789.   long int data_offset;
  790.  
  791.   /* Data relocation. */
  792.   unsigned long int data_reloc_size;
  793.   long int data_reloc_offset;
  794.  
  795.   /* The bss section. */
  796.   unsigned long int orig_bss_address;
  797.   unsigned long int bss_size;
  798.  
  799.   /* The symbol and string tables. */
  800.   unsigned long int syms_size;
  801.   long int syms_offset;
  802.   unsigned long int strs_size;
  803.   long int strs_offset;
  804.  
  805.   /* The GDB symbol segment, if any. */
  806.   unsigned long int symseg_size;
  807.   long int symseg_offset;
  808.  
  809. #ifdef MACH_O
  810.   /* Section ordinals from the Mach-O load commands.  These
  811.      are compared with the n_sect fields of symbols.  */
  812.   int text_ordinal;
  813.   int data_ordinal;
  814.   int bss_ordinal;
  815. #endif
  816.  
  817.   /* Describe data from the file loaded into core */
  818.  
  819.   /* Symbol table of the file.  */
  820.   struct nlist *symbols;
  821.  
  822.   /* Pointer to the string table.
  823.      The string table is not kept in core all the time,
  824.      but when it is in core, its address is here.  */
  825.   char *strings;
  826.  
  827.   /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
  828.   /* output of undefined reference line numbers. */
  829.  
  830.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  831.   struct relocation_info *textrel;
  832.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  833.   struct relocation_info *datarel;
  834.  
  835.   /* Relation of this file's segments to the output file */
  836.  
  837.   /* Start of this file's text seg in the output file core image.  */
  838.   int text_start_address;
  839.   /* Start of this file's data seg in the output file core image.  */
  840.   int data_start_address;
  841.   /* Start of this file's bss seg in the output file core image.  */
  842.   int bss_start_address;
  843.   /* Offset in bytes in the output file symbol table
  844.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  845.   int local_syms_offset;
  846.  
  847.   /* For library members only */
  848.  
  849.   /* For a library, points to chain of entries for the library members.  */
  850.   struct file_entry *subfiles;
  851.   /* For a library member, offset of the member within the archive.
  852.      Zero for files that are not library members.  */
  853.   int starting_offset;
  854.   /* Size of contents of this file, if library member.  */
  855.   int total_size;
  856.   /* For library member, points to the library's own entry.  */
  857.   struct file_entry *superfile;
  858.   /* For library member, points to next entry for next member.  */
  859.   struct file_entry *chain;
  860.  
  861.   /* 1 if file is a library. */
  862.   char library_flag;
  863.  
  864.   /* 1 if file's header has been read into this structure.  */
  865.   char header_read_flag;
  866.  
  867.   /* 1 means search a set of directories for this file.  */
  868.   char search_dirs_flag;
  869.  
  870.   /* 1 means this is base file of incremental load.
  871.      Do not load this file's text or data.
  872.      Also default text_start to after this file's bss. */
  873.   char just_syms_flag;
  874. };
  875.  
  876. /* Vector of entries for input files specified by arguments.
  877.    These are all the input files except for members of specified libraries.  */
  878. struct file_entry *file_table;
  879.  
  880. /* Length of that vector.  */
  881. int number_of_files;
  882.  
  883. /* When loading the text and data, we can avoid doing a close
  884.    and another open between members of the same library.
  885.  
  886.    These two variables remember the file that is currently open.
  887.    Both are zero if no file is open.
  888.  
  889.    See `each_file' and `file_close'.  */
  890.  
  891. struct file_entry *input_file;
  892. int input_desc;
  893.  
  894. /* The name of the file to write; "a.out" by default.  */
  895.  
  896. char *output_filename;
  897.  
  898. /* What kind of output file to write.  */
  899.  
  900. enum file_type output_file_type;
  901.  
  902. #ifndef DEFAULT_OUTPUT_FILE_TYPE
  903. #ifdef MACH_O
  904. #define DEFAULT_OUTPUT_FILE_TYPE IS_MACH_O
  905. #else
  906. #define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
  907. #endif
  908. #endif
  909.  
  910. /* What `style' of output file to write.  For BSD a.out files
  911.    this specifies OMAGIC, NMAGIC, or ZMAGIC.  For Mach-O files
  912.    this switches between MH_OBJECT and two flavors of MH_EXECUTE.  */
  913.  
  914. enum output_style
  915.   {
  916.     OUTPUT_UNSPECIFIED,
  917.     OUTPUT_RELOCATABLE,        /* -r */
  918.     OUTPUT_WRITABLE_TEXT,    /* -N */
  919.     OUTPUT_READONLY_TEXT,    /* -n */
  920.     OUTPUT_DEMAND_PAGED        /* -Z (default) */
  921.   };
  922.  
  923. enum output_style output_style;
  924.  
  925. #ifndef DEFAULT_OUTPUT_STYLE
  926. #define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
  927. #endif
  928.  
  929. /* Descriptor for writing that file with `mywrite'.  */
  930.  
  931. int outdesc;
  932.  
  933. /* The following are computed by `digest_symbols'.  */
  934.  
  935. int text_size;            /* total size of text of all input files.  */
  936. int text_header_size;        /* size of the file header if included in the
  937.                    text size.  */
  938. int data_size;            /* total size of data of all input files.  */
  939. int bss_size;            /* total size of bss of all input files.  */
  940. int text_reloc_size;        /* total size of text relocation of all input files.  */
  941. int data_reloc_size;        /* total size of data relocation of all input
  942.                    files.  */
  943.   
  944. /* The following are computed by write_header().  */
  945. long int output_text_offset;    /* file offset of the text section.  */
  946. long int output_data_offset;    /* file offset of the data section.  */
  947. long int output_trel_offset;    /* file offset of the text relocation info.  */
  948. long int output_drel_offset;    /* file offset of the data relocation info.  */
  949. long int output_syms_offset;    /* file offset of the symbol table.  */
  950. long int output_strs_offset;    /* file offset of the string table.  */
  951.  
  952. /* The following are incrementally computed by write_syms(); we keep
  953.    them here so we can examine their values afterwards.  */
  954. unsigned int output_syms_size;    /* total bytes of symbol table output. */
  955. unsigned int output_strs_size;    /* total bytes of string table output. */
  956.  
  957. /* This can only be computed after the size of the string table is known.  */
  958. long int output_symseg_offset;    /* file offset of the symbol segment (if any).  */
  959.  
  960. /* Incrementally computed by write_file_symseg().  */
  961. unsigned int output_symseg_size;
  962.  
  963. /* Specifications of start and length of the area reserved at the end
  964.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  965. int set_sect_start;
  966. int set_sect_size;
  967.  
  968. /* Pointer for in core storage for the above vectors, before they are
  969.    written. */
  970. unsigned long *set_vectors;
  971.  
  972. /* Amount of cleared space to leave at the end of the text segment.  */
  973.  
  974. int text_pad;
  975.  
  976. /* Amount of padding at end of data segment.  This has two parts:
  977.    That which is before the bss segment, and that which overlaps
  978.    with the bss segment.  */
  979. int data_pad;
  980.  
  981. /* Format of __.SYMDEF:
  982.    First, a longword containing the size of the 'symdef' data that follows.
  983.    Second, zero or more 'symdef' structures.
  984.    Third, a longword containing the length of symbol name strings.
  985.    Fourth, zero or more symbol name strings (each followed by a null).  */
  986.  
  987. struct symdef {
  988.   int symbol_name_string_index;
  989.   int library_member_offset;
  990. };
  991.  
  992. /* Record most of the command options.  */
  993.  
  994. /* Address we assume the text section will be loaded at.
  995.    We relocate symbols and text and data for this, but we do not
  996.    write any padding in the output file for it.  */
  997. int text_start;
  998.  
  999. /* Address we decide the data section will be loaded at.  */
  1000. int data_start;
  1001.  
  1002. /* Nonzero if -T was specified in the command line.
  1003.    This prevents text_start from being set later to default values.  */
  1004. int T_flag_specified;
  1005.  
  1006. /* Nonzero if -Tdata was specified in the command line.
  1007.    This prevents data_start from being set later to default values.  */
  1008. int Tdata_flag_specified;
  1009.  
  1010. /* Size to pad data section up to.
  1011.    We simply increase the size of the data section, padding with zeros,
  1012.    and reduce the size of the bss section to match.  */
  1013. int specified_data_size;
  1014.  
  1015. /* Nonzero means print names of input files as processed.  */
  1016. int trace_files;
  1017.  
  1018. /* Which symbols should be stripped (omitted from the output):
  1019.    none, all, or debugger symbols.  */
  1020. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  1021.  
  1022. /* Which local symbols should be omitted:
  1023.    none, all, or those starting with L.
  1024.    This is irrelevant if STRIP_NONE.  */
  1025. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  1026.  
  1027. /* 1 => write load map.  */
  1028. int write_map;
  1029.  
  1030. /* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
  1031. int force_common_definition;
  1032.  
  1033. /* Standard directories to search for files specified by -l.  */
  1034. char *standard_search_dirs[] =
  1035. #ifdef STANDARD_SEARCH_DIRS
  1036.   {STANDARD_SEARCH_DIRS};
  1037. #else
  1038. #ifdef NON_NATIVE
  1039.   {"/usr/local/lib/gnu"};
  1040. #else
  1041.   {"/lib", "/usr/lib", "/usr/local/lib"};
  1042. #endif
  1043. #endif
  1044.  
  1045. /* If set STANDARD_SEARCH_DIRS is not searched.  */
  1046. int no_standard_dirs;
  1047.  
  1048. /* Actual vector of directories to search;
  1049.    this contains those specified with -L plus the standard ones.  */
  1050. char **search_dirs;
  1051.  
  1052. /* Length of the vector `search_dirs'.  */
  1053. int n_search_dirs;
  1054.  
  1055. /* Non zero means to create the output executable.
  1056.    Cleared by nonfatal errors.  */
  1057. int make_executable;
  1058.  
  1059. /* Force the executable to be output, even if there are non-fatal
  1060.    errors */
  1061. int force_executable;
  1062.  
  1063. /* Keep a list of any symbols referenced from the command line (so
  1064.    that error messages for these guys can be generated). This list is
  1065.    zero terminated. */
  1066. struct glosym **cmdline_references;
  1067. int cl_refs_allocated;
  1068.  
  1069. #ifndef bcopy
  1070. void bcopy (), bzero ();
  1071. #endif
  1072. #ifndef __STDC__
  1073. char *malloc (), *realloc ();
  1074. void free ();
  1075. #endif
  1076.  
  1077. char *xmalloc ();
  1078. char *xrealloc ();
  1079. void usage ();
  1080. void fatal ();
  1081. void fatal_with_file ();
  1082. void perror_name ();
  1083. void perror_file ();
  1084. void error ();
  1085.  
  1086. int parse ();
  1087. void initialize_text_start ();
  1088. void initialize_data_start ();
  1089. void digest_symbols ();
  1090. void print_symbols ();
  1091. void load_symbols ();
  1092. void decode_command ();
  1093. void list_undefined_symbols ();
  1094. void list_unresolved_references ();
  1095. void write_output ();
  1096. void write_header ();
  1097. void write_text ();
  1098. #ifdef HUNK_INSTEAD_OF_A_OUT
  1099. void write_hunk_header ();
  1100. void conditionally_rewrite_headers ();
  1101. void write_bss ();
  1102. void init_reloc_hunk ();
  1103. void add_to_reloc_hunk ();
  1104. void write_reloc_hunk ();
  1105. void init_symbol_hunks ();
  1106. void add_to_symbol_hunk ();
  1107. void write_symbol_hunk ();
  1108. void look_for_symbols ();
  1109. void look_for_file_symbols ();
  1110. void relocate_set_vectors ();
  1111. #endif
  1112. void read_file_relocation ();
  1113. void write_data ();
  1114. void write_rel ();
  1115. void write_syms ();
  1116. void write_symsegs ();
  1117. void mywrite ();
  1118. void symtab_init ();
  1119. void padfile ();
  1120. char *concat ();
  1121. char *get_file_name ();
  1122. symbol *getsym (), *getsym_soft ();
  1123.  
  1124. int
  1125. main (argc, argv)
  1126.      char **argv;
  1127.      int argc;
  1128. {
  1129.   page_size = getpagesize ();
  1130.   progname = argv[0];
  1131.  
  1132. #ifdef RLIMIT_STACK
  1133.   /* Avoid dumping core on large .o files.  */
  1134.   {
  1135.     struct rlimit rl;
  1136.  
  1137.     getrlimit (RLIMIT_STACK, &rl);
  1138.     rl.rlim_cur = rl.rlim_max;
  1139.     setrlimit (RLIMIT_STACK, &rl);
  1140.   }
  1141. #endif
  1142.  
  1143.   /* Clear the cumulative info on the output file.  */
  1144.  
  1145.   text_size = 0;
  1146.   data_size = 0;
  1147.   bss_size = 0;
  1148.   text_reloc_size = 0;
  1149.   data_reloc_size = 0;
  1150.  
  1151.   data_pad = 0;
  1152.   text_pad = 0;
  1153.  
  1154.   /* Initialize the data about options.  */
  1155.  
  1156.   specified_data_size = 0;
  1157.   strip_symbols = STRIP_NONE;
  1158.   trace_files = 0;
  1159.   discard_locals = DISCARD_NONE;
  1160.   entry_symbol = 0;
  1161.   write_map = 0;
  1162.   force_common_definition = 0;
  1163.   T_flag_specified = 0;
  1164.   Tdata_flag_specified = 0;
  1165.   make_executable = 1;
  1166.   force_executable = 0;
  1167.   set_element_prefixes = 0;
  1168. #ifdef HUNK_INSTEAD_OF_A_OUT
  1169.   amiga_symbols_only = 1;
  1170. #endif
  1171.  
  1172.   /* Initialize the cumulative counts of symbols.  */
  1173.  
  1174.   local_sym_count = 0;
  1175.   non_L_local_sym_count = 0;
  1176.   debugger_sym_count = 0;
  1177.   undefined_global_sym_count = 0;
  1178.   set_symbol_count = 0;
  1179.   set_vector_count = 0;
  1180.   global_indirect_count = 0;
  1181.   warning_count = 0;
  1182.   multiple_def_count = 0;
  1183.   common_defined_global_count = 0;
  1184.  
  1185.   /* Keep a list of symbols referenced from the command line */
  1186.  
  1187.   cl_refs_allocated = 10;
  1188.   cmdline_references
  1189.     = (struct glosym **) xmalloc (cl_refs_allocated
  1190.                   * sizeof(struct glosym *));
  1191.   *cmdline_references = 0;
  1192.  
  1193.   /* Completely decode ARGV.  */
  1194.  
  1195.   decode_command (argc, argv);
  1196.  
  1197.   /* Load symbols of all input files.
  1198.      Also search all libraries and decide which library members to load.  */
  1199.  
  1200.   load_symbols ();
  1201.  
  1202.   /* Create various built-in symbols.  This must occur after
  1203.      all input files are loaded so that a user program can have a
  1204.      symbol named etext (for example).  */
  1205.  
  1206.   if (output_style != OUTPUT_RELOCATABLE)
  1207.     symtab_init ();
  1208.  
  1209.   /* Compute where each file's sections go, and relocate symbols.  */
  1210.  
  1211.   digest_symbols ();
  1212.  
  1213.   /* Print error messages for any missing symbols, for any warning
  1214.      symbols, and possibly multiple definitions */
  1215.  
  1216.   do_warnings (stderr);
  1217.  
  1218.   /* Print a map, if requested.  */
  1219.  
  1220.   if (write_map) print_symbols (stdout);
  1221.  
  1222.   /* Write the output file.  */
  1223.  
  1224.   if (make_executable || force_executable)
  1225.     write_output ();
  1226.  
  1227.   exit (!make_executable);
  1228. }
  1229.  
  1230. void add_cmdline_ref ();
  1231.  
  1232. static struct option longopts[] =
  1233. {
  1234. #ifdef HUNK_INSTEAD_OF_A_OUT
  1235.   {"amiga-debug-hunk", 0, 0, 'a'},
  1236.   {"databss-together", 0, 0, 'b'},
  1237.   {"datadata-reloc", 0, 0, 'c'},
  1238.   {"msmall-code", 0, 0, 129},        /* ignore.. */
  1239. #endif
  1240.   {"d", 0, 0, 'd'},
  1241.   {"dc", 0, 0, 'd'},        /* For Sun compatibility. */
  1242.   {"dp", 0, 0, 'd'},        /* For Sun compatibility. */
  1243.   {"e", 1, 0, 'e'},
  1244.   {"n", 0, 0, 'n'},
  1245.   {"noinhibit-exec", 0, 0, 130},
  1246.   {"nostdlib", 0, 0, 133},
  1247.   {"o", 1, 0, 'o'},
  1248.   {"r", 0, 0, 'r'},
  1249.   {"s", 0, 0, 's'},
  1250.   {"t", 0, 0, 't'},
  1251.   {"u", 1, 0, 'u'},
  1252.   {"x", 0, 0, 'x'},
  1253.   {"z", 0, 0, 'z'},
  1254.   {"A", 1, 0, 'A'},
  1255.   {"Bstatic", 0, 0, 129},    /* For Sun compatibility. */
  1256.   {"D", 1, 0, 'D'},
  1257.   {"M", 0, 0, 'M'},
  1258.   {"N", 0, 0, 'N'},
  1259.   {"S", 0, 0, 'S'},
  1260.   {"T", 1, 0, 'T'},
  1261.   {"Ttext", 1, 0, 'T'},
  1262.   {"Tdata", 1, 0, 132},
  1263.   {"V", 1, 0, 'V'},
  1264.   {"X", 0, 0, 'X'},
  1265.   {0, 0, 0, 0}
  1266. };
  1267.  
  1268. /* Since the Unix ld accepts -lfoo, -Lfoo, and -yfoo, we must also.
  1269.    This effectively prevents any long options from starting with
  1270.    one of these letters. */
  1271. #define SHORTOPTS "-l:y:L:"
  1272.  
  1273. /* Process the command arguments,
  1274.    setting up file_table with an entry for each input file,
  1275.    and setting variables according to the options.  */
  1276.  
  1277. void
  1278. decode_command (argc, argv)
  1279.      char **argv;
  1280.      int argc;
  1281. {
  1282.   int optc, longind;
  1283.   register struct file_entry *p;
  1284.  
  1285.   number_of_files = 0;
  1286.   output_filename = "a.out";
  1287.  
  1288.   n_search_dirs = 0;
  1289.   search_dirs = (char **) xmalloc (sizeof (char *));
  1290.  
  1291.   /* First compute number_of_files so we know how long to make file_table.
  1292.      Also process most options completely.  */
  1293.  
  1294.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1295.      != EOF)
  1296.     {
  1297.       if (optc == 0)
  1298.     optc = longopts[longind].val;
  1299.  
  1300.       switch (optc)
  1301.     {
  1302.     case '?':
  1303.       usage (0, 0);
  1304.       break;
  1305.  
  1306.     case 1:
  1307.       /* Non-option argument. */
  1308.       number_of_files++;
  1309.       break;
  1310.  
  1311. #ifdef HUNK_INSTEAD_OF_A_OUT
  1312.     case 'a':
  1313.       amiga_symbols_only = 0;
  1314.       break;
  1315.  
  1316.     case 'b':
  1317.       databss_together = 1;
  1318.       break;
  1319.  
  1320.     case 'c':
  1321.       output_datadata_relocs = 1;
  1322.       break;
  1323. #endif
  1324.  
  1325.     case 'd':
  1326.       force_common_definition = 1;
  1327.       break;
  1328.  
  1329.     case 'e':
  1330.       entry_symbol = getsym (optarg);
  1331.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1332.         undefined_global_sym_count++;
  1333.       entry_symbol->referenced = 1;
  1334.       add_cmdline_ref (entry_symbol);
  1335.       break;
  1336.  
  1337.     case 'l':
  1338.       number_of_files++;
  1339.       break;
  1340.  
  1341.     case 'n':
  1342.       if (output_style && output_style != OUTPUT_READONLY_TEXT)
  1343.         fatal ("illegal combination of -n with -N, -r, or -z", (char *) 0);
  1344.       output_style = OUTPUT_READONLY_TEXT;
  1345.       break;
  1346.  
  1347.     case 130:        /* -noinhibit-exec */
  1348.       force_executable = 1;
  1349.       break;
  1350.  
  1351.     case 133:        /* -nostdlib */
  1352.       no_standard_dirs = 1;
  1353.       break;
  1354.  
  1355.     case 'o':
  1356.       output_filename = optarg;
  1357.       break;
  1358.  
  1359.     case 'r':
  1360.       if (output_style && output_style != OUTPUT_RELOCATABLE)
  1361.         fatal ("illegal combination of -r with -N, -n, or -z", (char *) 0);
  1362.       output_style = OUTPUT_RELOCATABLE;
  1363.       text_start = 0;
  1364.       break;
  1365.  
  1366.     case 's':
  1367.       strip_symbols = STRIP_ALL;
  1368.       break;
  1369.  
  1370.     case 't':
  1371.       trace_files = 1;
  1372.       break;
  1373.  
  1374.     case 'u':
  1375.       {
  1376.         register symbol *sp = getsym (optarg);
  1377.  
  1378.         if (!sp->defined && !sp->referenced)
  1379.           undefined_global_sym_count++;
  1380.         sp->referenced = 1;
  1381.         add_cmdline_ref (sp);
  1382.       }
  1383.       break;
  1384.  
  1385.     case 'x':
  1386.       discard_locals = DISCARD_ALL;
  1387.       break;
  1388.       
  1389.     case 'y':
  1390.       {
  1391.         register symbol *sp = getsym (optarg);
  1392.  
  1393.         sp->trace = 1;
  1394.       }
  1395.       break;
  1396.  
  1397.     case 'z':
  1398.       if (output_style && output_style != OUTPUT_DEMAND_PAGED)
  1399.         fatal ("illegal combination of -z with -N, -n, or -r", (char *) 0);
  1400.       output_style = OUTPUT_DEMAND_PAGED;
  1401.       break;
  1402.  
  1403.     case 'A':
  1404.       number_of_files++;
  1405.       break;
  1406.  
  1407.     case 129:        /* -Bstatic. */
  1408.       /* Ignore. */
  1409.       break;
  1410.  
  1411.     case 'D':
  1412.       specified_data_size = parse (optarg, "%x", "invalid argument to -D");
  1413.       break;
  1414.  
  1415.     case 'L':
  1416.       n_search_dirs++;
  1417.       search_dirs = (char **)
  1418.         xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1419.       search_dirs[n_search_dirs - 1] = optarg;
  1420.       break;
  1421.       
  1422.     case 'M':
  1423.       write_map = 1;
  1424.       break;
  1425.  
  1426.     case 'N':
  1427.       if (output_style && output_style != OUTPUT_WRITABLE_TEXT)
  1428.         fatal ("illegal combination of -N with -n, -r, or -z", (char *) 0);
  1429.       output_style = OUTPUT_WRITABLE_TEXT;
  1430.       break;
  1431.  
  1432.     case 'S':
  1433.       strip_symbols = STRIP_DEBUGGER;
  1434.       break;
  1435.  
  1436.     case 'T':
  1437.       text_start = parse (optarg, "%x", "invalid argument to -Ttext");
  1438.       T_flag_specified = 1;
  1439.       break;
  1440.  
  1441.     case 132:        /* -Tdata addr */
  1442.       data_start = parse (optarg, "%x", "invalid argument to -Tdata");
  1443.       Tdata_flag_specified = 1;
  1444.       break;
  1445.  
  1446.     case 'V':
  1447.       {
  1448.         struct string_list_element *new
  1449.           = (struct string_list_element *)
  1450.         xmalloc (sizeof (struct string_list_element));
  1451.         
  1452.         new->str = optarg;
  1453.         new->next = set_element_prefixes;
  1454.         set_element_prefixes = new;
  1455.       }
  1456.       break;
  1457.  
  1458.     case 'X':
  1459.       discard_locals = DISCARD_L;
  1460.       break;
  1461.     }
  1462.     }
  1463.  
  1464.   if (!number_of_files)
  1465.     usage ("no input files", 0);
  1466.  
  1467.   p = file_table
  1468.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1469.   bzero (p, number_of_files * sizeof (struct file_entry));
  1470.  
  1471.   /* Now scan again and fill in file_table.
  1472.      All options except -A and -l are ignored here.  */
  1473.  
  1474.   optind = 0;            /* Reset getopt. */
  1475.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1476.      != EOF)
  1477.     {
  1478.       if (optc == 0)
  1479.     optc = longopts[longind].val;
  1480.  
  1481.       switch (optc)
  1482.     {
  1483.     case 1:
  1484.       /* Non-option argument. */
  1485.       p->filename = optarg;
  1486.       p->local_sym_name = optarg;
  1487.       p++;
  1488.       break;
  1489.  
  1490.     case 'A':
  1491.       if (p != file_table)
  1492.         usage ("-A specified before an input file other than the first");
  1493.       p->filename = optarg;
  1494.       p->local_sym_name = optarg;
  1495.       p->just_syms_flag = 1;
  1496.       p++;
  1497.       break;
  1498.  
  1499.     case 'l':
  1500.       p->filename = concat ("lib", optarg, ".a");
  1501.       p->local_sym_name = concat ("-l", optarg, "");
  1502.       p->search_dirs_flag = 1;
  1503.       p++;
  1504.       break;
  1505.     }
  1506.     }
  1507.  
  1508.   if (!output_file_type)
  1509.     output_file_type = DEFAULT_OUTPUT_FILE_TYPE;
  1510.  
  1511.   if (!output_style)
  1512.     output_style = DEFAULT_OUTPUT_STYLE;
  1513.  
  1514. #if 0
  1515.   /* THIS CONSISTENCY CHECK BELONGS SOMEWHERE ELSE.  */
  1516.   /* Now check some option settings for consistency.  */
  1517.  
  1518.   if ((output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  1519.       && (text_start - text_start_alignment) & (page_size - 1))
  1520.     usage ("-T argument not multiple of page size, with sharable output", 0);
  1521. #endif
  1522.  
  1523.   /* Append the standard search directories to the user-specified ones.  */
  1524.   if (!no_standard_dirs)
  1525.     {
  1526.       int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1527.       n_search_dirs += n;
  1528.       search_dirs
  1529.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1530.       bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1531.          n * sizeof (char *));
  1532.     }
  1533. }
  1534.  
  1535.  
  1536. void
  1537. add_cmdline_ref (sp)
  1538.      struct glosym *sp;
  1539. {
  1540.   struct glosym **ptr;
  1541.  
  1542.   for (ptr = cmdline_references;
  1543.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1544.        ptr++)
  1545.     ;
  1546.  
  1547.   if (ptr >= cmdline_references + cl_refs_allocated - 1)
  1548.     {
  1549.       int diff = ptr - cmdline_references;
  1550.  
  1551.       cl_refs_allocated *= 2;
  1552.       cmdline_references = (struct glosym **)
  1553.     xrealloc (cmdline_references,
  1554.          cl_refs_allocated * sizeof (struct glosym *));
  1555.       ptr = cmdline_references + diff;
  1556.     }
  1557.  
  1558.   *ptr++ = sp;
  1559.   *ptr = (struct glosym *) 0;
  1560. }
  1561.  
  1562. int
  1563. set_element_prefixed_p (name)
  1564.      char *name;
  1565. {
  1566.   struct string_list_element *p;
  1567.   int i;
  1568.  
  1569.   for (p = set_element_prefixes; p; p = p->next)
  1570.     {
  1571.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1572.     ;
  1573.  
  1574.       if (p->str[i] == '\0')
  1575.     return 1;
  1576.     }
  1577.   return 0;
  1578. }
  1579.  
  1580. /* Convenient functions for operating on one or all files being
  1581.    loaded.  */
  1582. void print_file_name ();
  1583.  
  1584. /* Call FUNCTION on each input file entry.
  1585.    Do not call for entries for libraries;
  1586.    instead, call once for each library member that is being loaded.
  1587.  
  1588.    FUNCTION receives two arguments: the entry, and ARG.  */
  1589.  
  1590. void
  1591. each_file (function, arg)
  1592.      register void (*function)();
  1593.      register int arg;
  1594. {
  1595.   register int i;
  1596.  
  1597.   for (i = 0; i < number_of_files; i++)
  1598.     {
  1599.       register struct file_entry *entry = &file_table[i];
  1600.       if (entry->library_flag)
  1601.         {
  1602.       register struct file_entry *subentry = entry->subfiles;
  1603.       for (; subentry; subentry = subentry->chain)
  1604.         (*function) (subentry, arg);
  1605.     }
  1606.       else
  1607.     (*function) (entry, arg);
  1608.     }
  1609. }
  1610.  
  1611. /* Call FUNCTION on each input file entry until it returns a non-zero
  1612.    value.  Return this value.
  1613.    Do not call for entries for libraries;
  1614.    instead, call once for each library member that is being loaded.
  1615.  
  1616.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1617.    function returning unsigned long (though this can probably be fudged). */
  1618.  
  1619. unsigned long
  1620. check_each_file (function, arg)
  1621.      register unsigned long (*function)();
  1622.      register int arg;
  1623. {
  1624.   register int i;
  1625.   register unsigned long return_val;
  1626.  
  1627.   for (i = 0; i < number_of_files; i++)
  1628.     {
  1629.       register struct file_entry *entry = &file_table[i];
  1630.       if (entry->library_flag)
  1631.         {
  1632.       register struct file_entry *subentry = entry->subfiles;
  1633.       for (; subentry; subentry = subentry->chain)
  1634.         if (return_val = (*function) (subentry, arg))
  1635.           return return_val;
  1636.     }
  1637.       else
  1638.     if (return_val = (*function) (entry, arg))
  1639.       return return_val;
  1640.     }
  1641.   return 0;
  1642. }
  1643.  
  1644. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1645.  
  1646. void
  1647. each_full_file (function, arg)
  1648.      register void (*function)();
  1649.      register int arg;
  1650. {
  1651.   register int i;
  1652.  
  1653.   for (i = 0; i < number_of_files; i++)
  1654.     {
  1655.       register struct file_entry *entry = &file_table[i];
  1656.       if (entry->just_syms_flag)
  1657.     continue;
  1658.       if (entry->library_flag)
  1659.         {
  1660.       register struct file_entry *subentry = entry->subfiles;
  1661.       for (; subentry; subentry = subentry->chain)
  1662.         (*function) (subentry, arg);
  1663.     }
  1664.       else
  1665.     (*function) (entry, arg);
  1666.     }
  1667. }
  1668.  
  1669. /* Close the input file that is now open.  */
  1670.  
  1671. void
  1672. file_close ()
  1673. {
  1674.   close (input_desc);
  1675.   input_desc = 0;
  1676.   input_file = 0;
  1677. }
  1678.  
  1679. /* Open the input file specified by 'entry', and return a descriptor.
  1680.    The open file is remembered; if the same file is opened twice in a row,
  1681.    a new open is not actually done.  */
  1682.  
  1683. int
  1684. file_open (entry)
  1685.      register struct file_entry *entry;
  1686. {
  1687.   register int desc;
  1688.  
  1689.   if (entry->superfile)
  1690.     return file_open (entry->superfile);
  1691.  
  1692.   if (entry == input_file)
  1693.     return input_desc;
  1694.  
  1695.   if (input_file) file_close ();
  1696.  
  1697.   if (entry->search_dirs_flag && n_search_dirs)
  1698.     {
  1699.       int i;
  1700.  
  1701.       for (i = 0; i < n_search_dirs; i++)
  1702.     {
  1703.       register char *string
  1704.         = concat (search_dirs[i], "/", entry->filename);
  1705.       desc = open (string, O_RDONLY, 0);
  1706.       if (desc > 0)
  1707.         {
  1708.           entry->filename = string;
  1709.           entry->search_dirs_flag = 0;
  1710.           break;
  1711.         }
  1712.       free (string);
  1713.     }
  1714.     }
  1715.   else
  1716.     desc = open (entry->filename, O_RDONLY, 0);
  1717.  
  1718.   if (desc > 0)
  1719.     {
  1720.       input_file = entry;
  1721.       input_desc = desc;
  1722.       return desc;
  1723.     }
  1724.  
  1725.   perror_file (entry);
  1726.   /* NOTREACHED */
  1727. }
  1728.  
  1729. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1730.    and then a newline.  */
  1731.  
  1732. void
  1733. prline_file_name (entry, outfile)
  1734.      struct file_entry *entry;
  1735.      FILE *outfile;
  1736. {
  1737.   print_file_name (entry, outfile);
  1738.   fprintf (outfile, "\n");
  1739. }
  1740.  
  1741. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1742.  
  1743. void
  1744. print_file_name (entry, outfile)
  1745.      struct file_entry *entry;
  1746.      FILE *outfile;
  1747. {
  1748.   if (entry->superfile)
  1749.     {
  1750.       print_file_name (entry->superfile, outfile);
  1751.       fprintf (outfile, "(%s)", entry->filename);
  1752.     }
  1753.   else
  1754.     fprintf (outfile, "%s", entry->filename);
  1755. }
  1756.  
  1757. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1758.  
  1759. char *
  1760. get_file_name (entry)
  1761.      struct file_entry *entry;
  1762. {
  1763.   char *result, *supfile;
  1764.   if (entry->superfile)
  1765.     {
  1766.       supfile = get_file_name (entry->superfile);
  1767.       result = (char *) xmalloc (strlen (supfile)
  1768.                  + strlen (entry->filename) + 3);
  1769.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1770.       free (supfile);
  1771.     }
  1772.   else
  1773.     {
  1774.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1775.       strcpy (result, entry->filename);
  1776.     }
  1777.   return result;
  1778. }
  1779.  
  1780. /* Medium-level input routines for rel files.  */
  1781.  
  1782. /* Determine whether the given ENTRY is an archive, a BSD a.out file,
  1783.    a Mach-O file, or whatever.  DESC is the descriptor on which the
  1784.    file is open.  */
  1785. void
  1786. deduce_file_type(desc, entry)
  1787.      int desc;
  1788.      struct file_entry *entry;
  1789. {
  1790.   int len;
  1791.  
  1792.   {
  1793.     char magic[SARMAG];
  1794.     
  1795.     lseek (desc, entry->starting_offset, 0);
  1796.     len = read (desc, magic, SARMAG);
  1797.     if (len == SARMAG && !strncmp(magic, ARMAG, SARMAG))
  1798.       {
  1799.     entry->file_type = IS_ARCHIVE;
  1800.     return;
  1801.       }
  1802.   }
  1803.  
  1804. #ifdef A_OUT
  1805.   {
  1806.     struct exec hdr;
  1807.  
  1808.     lseek (desc, entry->starting_offset, 0);
  1809. #ifdef COFF_ENCAPSULATE
  1810.     if (entry->just_syms_flag)
  1811.       /* Since a file given with -A will have a coff header, unlike normal
  1812.     input files, we need to skip over it.  */
  1813.       lseek (desc, sizeof (coffheader), SEEK_CUR);
  1814. #endif
  1815.     len = read (desc, (char *) &hdr, sizeof (struct exec));
  1816.     if (len == sizeof (struct exec) && !N_BADMAG (hdr))
  1817.       {
  1818.     entry->file_type = IS_A_OUT;
  1819.     return;
  1820.       }
  1821.   }
  1822. #endif
  1823.  
  1824. #ifdef MACH_O
  1825.   {
  1826.     struct mach_header hdr;
  1827.  
  1828.     lseek (desc, entry->starting_offset, 0);
  1829.     len = read (desc, (char *) &hdr, sizeof (struct mach_header));
  1830.     if (len == sizeof (struct mach_header) && hdr.magic == MH_MAGIC)
  1831.       {
  1832.     entry->file_type = IS_MACH_O;
  1833.     return;
  1834.       }
  1835.   }
  1836. #endif
  1837.  
  1838.   fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1839. }
  1840.  
  1841. #ifdef A_OUT
  1842. /* Read an a.out file's header and set up the fields of
  1843.    the ENTRY accordingly.  DESC is the descriptor on which
  1844.    the file is open.  */
  1845. void
  1846. read_a_out_header (desc, entry)
  1847.      int desc;
  1848.      struct file_entry *entry;
  1849. {
  1850.   register int len;
  1851.   struct exec hdr;
  1852.   struct stat st;
  1853.  
  1854.   lseek (desc, entry->starting_offset, 0);
  1855.  
  1856. #ifdef COFF_ENCAPSULATE
  1857.   if (entry->just_syms_flag)
  1858.     /* Since a file given with -A will have a coff header, unlike normal
  1859.        input files, we need to skip over it.  */
  1860.     lseek (desc, sizeof (coffheader), SEEK_CUR);
  1861. #endif
  1862.  
  1863.   read (desc, (char *) &hdr, sizeof (struct exec));
  1864.  
  1865. #ifdef READ_HEADER_HOOK
  1866.   READ_HEADER_HOOK(hdr.a_machtype);
  1867. #endif
  1868.  
  1869.   if (entry->just_syms_flag)
  1870.     entry->orig_text_address = N_TXTADDR(hdr);
  1871.   else
  1872.     entry->orig_text_address = 0;
  1873.   entry->text_size = hdr.a_text;
  1874.   entry->text_offset = N_TXTOFF(hdr);
  1875.  
  1876.   entry->text_reloc_size = hdr.a_trsize;
  1877. #ifdef N_TRELOFF
  1878.   entry->text_reloc_offset = N_TRELOFF(hdr);
  1879. #else
  1880. #ifdef N_DATOFF
  1881.   entry->text_reloc_offset = N_DATOFF(hdr) + hdr.a_data;
  1882. #else
  1883.   entry->text_reloc_offset = N_TXTOFF(hdr) + hdr.a_text + hdr.a_data;
  1884. #endif
  1885. #endif
  1886.  
  1887.   if (entry->just_syms_flag)
  1888.     entry->orig_data_address = N_DATADDR(hdr);
  1889.   else
  1890.     entry->orig_data_address = entry->text_size;
  1891.   entry->data_size = hdr.a_data;
  1892. #ifdef N_DATOFF
  1893.   entry->data_offset = N_DATOFF(hdr);
  1894. #else
  1895.   entry->data_offset = N_TXTOFF(hdr) + hdr.a_text;
  1896. #endif
  1897.  
  1898.   entry->data_reloc_size = hdr.a_drsize;
  1899. #ifdef N_DRELOFF
  1900.   entry->data_reloc_offset = N_DRELOFF(hdr);
  1901. #else
  1902.   entry->data_reloc_offset = entry->text_reloc_offset + entry->text_reloc_size;
  1903. #endif
  1904.  
  1905. #ifdef N_BSSADDR
  1906.   if (entry->just_syms_flag)
  1907.     entry->orig_bss_address = N_BSSADDR(hdr);
  1908.   else
  1909. #endif
  1910.   entry->orig_bss_address = entry->orig_data_address + entry->data_size;
  1911.   entry->bss_size = hdr.a_bss;
  1912.  
  1913.   entry->syms_size = hdr.a_syms;
  1914.   entry->syms_offset = N_SYMOFF(hdr);
  1915.   entry->strs_offset = N_STROFF(hdr);
  1916.   lseek(desc, entry->starting_offset + entry->strs_offset, 0);
  1917.   if (read(desc, (char *) &entry->strs_size, sizeof (unsigned long int))
  1918.       != sizeof (unsigned long int))
  1919.     fatal_with_file ("failure reading string table size of ", entry);
  1920.  
  1921.   if (!entry->superfile)
  1922.     {
  1923.       fstat(desc, &st);
  1924.       if (st.st_size > entry->strs_offset + entry->strs_size)
  1925.     {
  1926.       entry->symseg_size = st.st_size - (entry->strs_offset + entry->strs_size);
  1927.       entry->symseg_offset = entry->strs_offset + entry->strs_size;
  1928.     }
  1929.     }
  1930.   else
  1931.     if (entry->total_size > entry->strs_offset + entry->strs_size)
  1932.       {
  1933.     entry->symseg_size = entry->total_size - (entry->strs_offset + entry->strs_size);
  1934.     entry->symseg_offset = entry->strs_offset + entry->strs_size;
  1935.       }
  1936. }
  1937. #endif
  1938.  
  1939. #ifdef MACH_O
  1940. /* Read a Mach-O file's header.  DESC is the descriptor on which the
  1941.    file is open, and ENTRY is the file's entry.  */
  1942. void
  1943. read_mach_o_header (desc, entry)
  1944.      int desc;
  1945.      struct file_entry *entry;
  1946. {
  1947.   struct mach_header mach_header;
  1948.   char *hdrbuf;
  1949.   struct load_command *load_command;
  1950.   struct segment_command *segment_command;
  1951.   struct section *section;
  1952.   struct symtab_command *symtab_command;
  1953. #ifdef LC_SYMSEG
  1954.   struct symseg_command *symseg_command;
  1955. #endif;
  1956.   int ordinal;
  1957.   int symtab_seen, symseg_seen;
  1958.   int len, cmd, seg;
  1959.  
  1960.   entry->text_ordinal = entry->data_ordinal = entry->bss_ordinal = 0;
  1961.   symtab_seen = symseg_seen = 0;
  1962.   ordinal = 1;
  1963.  
  1964.   lseek (desc, entry->starting_offset, 0);
  1965.   len = read (desc, (char *) &mach_header, sizeof (struct mach_header));
  1966.   if (len != sizeof (struct mach_header))
  1967.     fatal_with_file ("failure reading Mach-O header of ", entry);
  1968.   if (mach_header.filetype != MH_OBJECT && mach_header.filetype != MH_EXECUTE)
  1969.     fatal_with_file ("unsupported Mach-O file type (not MH_OBJECT or MH_EXECUTE) in ", entry);
  1970.   hdrbuf = xmalloc (mach_header.sizeofcmds);
  1971.   len = read (desc, hdrbuf, mach_header.sizeofcmds);
  1972.   if (len != mach_header.sizeofcmds)
  1973.     fatal_with_file ("failure reading Mach-O load commands of ", entry);
  1974.   load_command = (struct load_command *) hdrbuf;
  1975.   for (cmd = 0; cmd < mach_header.ncmds; ++cmd)
  1976.     {
  1977.       switch (load_command->cmd)
  1978.     {
  1979.     case LC_SEGMENT:
  1980.       segment_command = (struct segment_command *) load_command;
  1981.       section = (struct section *) ((char *) (segment_command + 1));
  1982.       for (seg = 0; seg < segment_command->nsects; ++seg, ++section, ++ordinal)
  1983.         {
  1984.           if (!strncmp(SECT_TEXT, section->sectname, sizeof section->sectname))
  1985.         if (entry->text_ordinal)
  1986.           fatal_with_file ("more than one __text section in ", entry);
  1987.         else
  1988.           {
  1989.             entry->text_ordinal = ordinal;
  1990.             entry->orig_text_address = section->addr;
  1991.             entry->text_size = section->size;
  1992.             entry->text_offset = section->offset;
  1993.             entry->text_reloc_size = section->nreloc * sizeof (struct relocation_info);
  1994.             entry->text_reloc_offset = section->reloff;
  1995.           }
  1996.           else if (!strncmp(SECT_DATA, section->sectname, sizeof section->sectname))
  1997.         if (entry->data_ordinal)
  1998.           fatal_with_file ("more than one __data section in ", entry);
  1999.         else
  2000.           {
  2001.             entry->data_ordinal = ordinal;
  2002.             entry->orig_data_address = section->addr;
  2003.             entry->data_size = section->size;
  2004.             entry->data_offset = section->offset;
  2005.             entry->data_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2006.             entry->data_reloc_offset = section->reloff;
  2007.           }
  2008.           else if (!strncmp(SECT_BSS, section->sectname, sizeof section->sectname))
  2009.         if (entry->bss_ordinal)
  2010.           fatal_with_file ("more than one __bss section in ", entry);
  2011.         else
  2012.           {
  2013.             entry->bss_ordinal = ordinal;
  2014.             entry->orig_bss_address = section->addr;
  2015.             entry->bss_size = section->size;
  2016.           }
  2017.           else
  2018.         if (section->size != 0)
  2019.           fprintf (stderr, "%s: warning: unknown section `%.*s' in %s\n",
  2020.                progname, sizeof section->sectname, section->sectname,
  2021.                entry->filename);
  2022.         }
  2023.       break;
  2024.     case LC_SYMTAB:
  2025.       if (symtab_seen)
  2026.           fatal_with_file ("more than one LC_SYMTAB in ", entry);
  2027.       else
  2028.         {
  2029.           symtab_seen = 1;
  2030.           symtab_command = (struct symtab_command *) load_command;
  2031.           entry->syms_size = symtab_command->nsyms * sizeof (struct nlist);
  2032.           entry->syms_offset = symtab_command->symoff;
  2033.           entry->strs_size = symtab_command->strsize;
  2034.           entry->strs_offset = symtab_command->stroff;
  2035.         }
  2036.       break;
  2037. #ifdef LC_SYMSEG
  2038.     case LC_SYMSEG:
  2039.       if (symseg_seen)
  2040.         fatal_with_file ("more than one LC_SYMSEG in ", entry);
  2041.       else
  2042.         {
  2043.           symseg_seen = 1;
  2044.           symseg_command = (struct symseg_command *) load_command;
  2045.           entry->symseg_size = symseg_command->size;
  2046.           entry->symseg_offset = symseg_command->offset;
  2047.         }
  2048.       break;
  2049. #endif
  2050.     }
  2051.       load_command = (struct load_command *)
  2052.     ((char *) load_command + load_command->cmdsize);
  2053.     }
  2054.  
  2055.   free (hdrbuf);
  2056.  
  2057.   if (!symtab_seen)
  2058.     fprintf (stderr, "%s: no symbol table in %s\n", progname, entry->filename);
  2059. }
  2060. #endif
  2061.  
  2062. /* Read a file's header info into the proper place in the file_entry.
  2063.    DESC is the descriptor on which the file is open.
  2064.    ENTRY is the file's entry.
  2065.    Switch in the file_type to determine the appropriate actual
  2066.    header reading routine to call.  */
  2067.  
  2068. void
  2069. read_header (desc, entry)
  2070.      int desc;
  2071.      register struct file_entry *entry;
  2072. {
  2073.   if (!entry->file_type)
  2074.     deduce_file_type (desc, entry);
  2075.  
  2076.   switch (entry->file_type)
  2077.     {
  2078.     case IS_ARCHIVE:
  2079.     default:
  2080.       /* Should never happen. */
  2081.       abort ();
  2082.  
  2083. #ifdef A_OUT
  2084.     case IS_A_OUT:
  2085.       read_a_out_header (desc, entry);
  2086.       break;
  2087. #endif
  2088.  
  2089. #ifdef MACH_O
  2090.     case IS_MACH_O:
  2091.       read_mach_o_header (desc, entry);
  2092.       break;
  2093. #endif
  2094.     }
  2095.  
  2096.   entry->header_read_flag = 1;
  2097. }
  2098.  
  2099. #ifdef MACH_O
  2100. void translate_mach_o_symbols ();
  2101. #endif
  2102.  
  2103. /* Read the symbols of file ENTRY into core.
  2104.    Assume it is already open, on descriptor DESC.  */
  2105.  
  2106. void
  2107. read_entry_symbols (desc, entry)
  2108.      struct file_entry *entry;
  2109.      int desc;
  2110. {
  2111.   int str_size;
  2112.  
  2113.   if (!entry->header_read_flag)
  2114.     read_header (desc, entry);
  2115.  
  2116.   entry->symbols = (struct nlist *) xmalloc (entry->syms_size);
  2117.  
  2118.   lseek (desc, entry->syms_offset + entry->starting_offset, 0);
  2119.   if (entry->syms_size != read (desc, entry->symbols, entry->syms_size))
  2120.     fatal_with_file ("premature end of file in symbols of ", entry);
  2121.  
  2122. #ifdef MACH_O
  2123.   if (entry->file_type == IS_MACH_O)
  2124.     translate_mach_o_symbols (entry);
  2125. #endif
  2126. }
  2127.  
  2128. /* Read the string table of file ENTRY into core.
  2129.    Assume it is already open, on descriptor DESC.  */
  2130.  
  2131. void
  2132. read_entry_strings (desc, entry)
  2133.      struct file_entry *entry;
  2134.      int desc;
  2135. {
  2136.   int buffer;
  2137.  
  2138.   if (!entry->header_read_flag)
  2139.     read_header (desc, entry);
  2140.  
  2141.   lseek (desc, entry->strs_offset + entry->starting_offset, 0);
  2142.   if (entry->strs_size != read (desc, entry->strings, entry->strs_size))
  2143.     fatal_with_file ("premature end of file in strings of ", entry);
  2144. }
  2145.  
  2146. /* Read in the symbols of all input files.  */
  2147.  
  2148. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  2149. void enter_file_symbols (), enter_global_ref (), search_library ();
  2150.  
  2151. void
  2152. load_symbols ()
  2153. {
  2154.   register int i;
  2155.  
  2156.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  2157.  
  2158.   for (i = 0; i < number_of_files; i++)
  2159.     {
  2160.       register struct file_entry *entry = &file_table[i];
  2161.       read_file_symbols (entry);
  2162.     }
  2163.  
  2164.   if (trace_files) fprintf (stderr, "\n");
  2165. }
  2166.  
  2167. /* If ENTRY is a rel file, read its symbol and string sections into core.
  2168.    If it is a library, search it and load the appropriate members
  2169.    (which means calling this function recursively on those members).  */
  2170.  
  2171. void
  2172. read_file_symbols (entry)
  2173.      register struct file_entry *entry;
  2174. {
  2175.   register int desc;
  2176.  
  2177.   desc = file_open (entry);
  2178.  
  2179.   if (!entry->file_type)
  2180.     deduce_file_type (desc, entry);
  2181.  
  2182.   if (entry->file_type == IS_ARCHIVE)
  2183.     {
  2184.       entry->library_flag = 1;
  2185.       search_library (desc, entry);
  2186.     }
  2187.   else
  2188.     {
  2189.       read_entry_symbols (desc, entry);
  2190.       entry->strings = (char *) alloca (entry->strs_size);
  2191.       read_entry_strings (desc, entry);
  2192.       enter_file_symbols (entry);
  2193.       entry->strings = 0;
  2194.     }
  2195.  
  2196.   file_close ();
  2197. }
  2198.  
  2199. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  2200.  
  2201. void
  2202. enter_file_symbols (entry)
  2203.      struct file_entry *entry;
  2204. {
  2205.   register struct nlist
  2206.     *p,
  2207.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2208.  
  2209.   if (trace_files) prline_file_name (entry, stderr);
  2210.  
  2211.   for (p = entry->symbols; p < end; p++)
  2212.     {
  2213.       if (p->n_type == (N_SETV | N_EXT)) continue;
  2214.       if (set_element_prefixes
  2215.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  2216.     p->n_type += (N_SETA - N_ABS);
  2217.  
  2218.       if (SET_ELEMENT_P (p->n_type))
  2219.     {
  2220.       set_symbol_count++;
  2221.       if (output_style != OUTPUT_RELOCATABLE)
  2222.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2223.     }
  2224.       else if (p->n_type == N_WARNING)
  2225.     {
  2226.       char *name = p->n_un.n_strx + entry->strings;
  2227.  
  2228.       /* Grab the next entry.  */
  2229.       p++;
  2230.       if (p->n_type != (N_UNDF | N_EXT))
  2231.         {
  2232.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  2233.                progname, entry->filename);
  2234.           make_executable = 0;
  2235.           p--;        /* Process normally.  */
  2236.         }
  2237.       else
  2238.         {
  2239.           symbol *sp;
  2240.           char *sname = p->n_un.n_strx + entry->strings;
  2241.           /* Deal with the warning symbol.  */
  2242.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2243.           sp = getsym (sname);
  2244.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  2245.           strcpy (sp->warning, name);
  2246.           warning_count++;
  2247.         }
  2248.     }
  2249.       else if (p->n_type & N_EXT)
  2250.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2251.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  2252.     {
  2253.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  2254.         non_L_local_sym_count++;
  2255.       local_sym_count++;
  2256.     }
  2257.       else debugger_sym_count++;
  2258.     }
  2259.  
  2260.    /* Count one for the local symbol that we generate,
  2261.       whose name is the file's name (usually) and whose address
  2262.       is the start of the file's text.  */
  2263.  
  2264.   local_sym_count++;
  2265.   non_L_local_sym_count++;
  2266. }
  2267.  
  2268. /* Enter one global symbol in the hash table.
  2269.    NLIST_P points to the `struct nlist' read from the file
  2270.    that describes the global symbol.  NAME is the symbol's name.
  2271.    ENTRY is the file entry for the file the symbol comes from.
  2272.  
  2273.    The `struct nlist' is modified by placing it on a chain of
  2274.    all such structs that refer to the same global symbol.
  2275.    This chain starts in the `refs' field of the symbol table entry
  2276.    and is chained through the `n_name'.  */
  2277.  
  2278. void
  2279. enter_global_ref (nlist_p, name, entry)
  2280.      register struct nlist *nlist_p;
  2281.      char *name;
  2282.      struct file_entry *entry;
  2283. {
  2284.   register symbol *sp = getsym (name);
  2285.   register int type = nlist_p->n_type;
  2286.   int oldref = sp->referenced;
  2287.   int olddef = sp->defined;
  2288.  
  2289.   nlist_p->n_un.n_name = (char *) sp->refs;
  2290.   sp->refs = nlist_p;
  2291.  
  2292.   sp->referenced = 1;
  2293.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  2294.     {
  2295.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  2296.     sp->defined = type;
  2297.  
  2298.       if (oldref && !olddef)
  2299.     /* It used to be undefined and we're defining it.  */
  2300.     undefined_global_sym_count--;
  2301.  
  2302.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  2303.     {
  2304.       /* First definition and it's common.  */
  2305.       common_defined_global_count++;
  2306.       sp->max_common_size = nlist_p->n_value;
  2307.     }
  2308.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  2309.     {
  2310.       /* It used to be common and we're defining it as
  2311.          something else.  */
  2312.       common_defined_global_count--;
  2313.       sp->max_common_size = 0;
  2314.     }
  2315.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  2316.       && sp->max_common_size < nlist_p->n_value)
  2317.     /* It used to be common and this is a new common entry to
  2318.        which we need to pay attention.  */
  2319.     sp->max_common_size = nlist_p->n_value;
  2320.  
  2321.       /* Are we defining it as a set element?  */
  2322.       if (SET_ELEMENT_P (type)
  2323.       && (!olddef || (olddef && sp->max_common_size)))
  2324.     set_vector_count++;
  2325.       /* As an indirection?  */
  2326.       else if (type == (N_INDR | N_EXT))
  2327.     {
  2328.       /* Indirect symbols value should be modified to point
  2329.          a symbol being equivalenced to. */
  2330.       nlist_p->n_value
  2331. #ifndef NeXT
  2332.         = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  2333.                      + entry->strings);
  2334. #else
  2335.         /* NeXT also has indirection but they do it weirdly. */
  2336.         = (unsigned int) getsym (nlist_p->n_value + entry->strings);
  2337. #endif
  2338.       if ((symbol *) nlist_p->n_value == sp)
  2339.         {
  2340.           /* Somebody redefined a symbol to be itself.  */
  2341.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  2342.                entry->filename, name);
  2343.           /* Rewrite this symbol as being a global text symbol
  2344.          with value 0.  */
  2345.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  2346.           nlist_p->n_value = 0;
  2347.           /* Don't make the output executable.  */
  2348.           make_executable = 0;
  2349.         }
  2350.       else
  2351.         global_indirect_count++;
  2352.     }
  2353.     }
  2354.   else
  2355.     if (!oldref)
  2356. #ifndef DOLLAR_KLUDGE
  2357.       undefined_global_sym_count++;
  2358. #else
  2359.       {
  2360.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  2361.       {
  2362.         /* This is an (ISI?) $-conditional; skip it */
  2363.         sp->referenced = 0;
  2364.         if (sp->trace)
  2365.           {
  2366.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  2367.         print_file_name (entry, stderr);
  2368.         fprintf (stderr, "\n");
  2369.           }
  2370.         return;
  2371.       }
  2372.     else
  2373.       undefined_global_sym_count++;
  2374.       }
  2375. #endif
  2376.  
  2377.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  2378.     text_start = nlist_p->n_value;
  2379.  
  2380.   if (sp->trace)
  2381.     {
  2382.       register char *reftype;
  2383.       switch (type & ~N_EXT)
  2384.     {
  2385.     case N_UNDF:
  2386.       if (nlist_p->n_value)
  2387.         reftype = "defined as common";
  2388.       else reftype = "referenced";
  2389.       break;
  2390.  
  2391.     case N_ABS:
  2392.       reftype = "defined as absolute";
  2393.       break;
  2394.  
  2395.     case N_TEXT:
  2396.       reftype = "defined in text section";
  2397.       break;
  2398.  
  2399.     case N_DATA:
  2400.       reftype = "defined in data section";
  2401.       break;
  2402.  
  2403.     case N_BSS:
  2404.       reftype = "defined in BSS section";
  2405.       break;
  2406.  
  2407.     case N_SETT:
  2408.       reftype = "is a text set element";
  2409.       break;
  2410.  
  2411.     case N_SETD:
  2412.       reftype = "is a data set element";
  2413.       break;
  2414.  
  2415.     case N_SETB:
  2416.       reftype = "is a BSS set element";
  2417.       break;
  2418.  
  2419.     case N_SETA:
  2420.       reftype = "is an absolute set element";
  2421.       break;
  2422.  
  2423.     case N_SETV:
  2424.       reftype = "defined in data section as vector";
  2425.       break;
  2426.  
  2427.     case N_INDR:
  2428.       reftype = (char *) alloca (23 + strlen (((symbol *) nlist_p->n_value)->name));
  2429.       sprintf (reftype, "defined equivalent to %s",
  2430.            ((symbol *) nlist_p->n_value)->name);
  2431.       break;
  2432.  
  2433. #ifdef sequent
  2434.     case N_SHUNDF:
  2435.       reftype = "shared undf";
  2436.       break;
  2437.  
  2438. /* These conflict with cases above.
  2439.     case N_SHDATA:
  2440.       reftype = "shared data";
  2441.       break;
  2442.  
  2443.     case N_SHBSS:
  2444.       reftype = "shared BSS";
  2445.       break;
  2446. */
  2447. #endif
  2448.  
  2449.     default:
  2450.       reftype = "I don't know this type";
  2451.       break;
  2452.     }
  2453.  
  2454.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2455.       print_file_name (entry, stderr);
  2456.       fprintf (stderr, "\n");
  2457.     }
  2458. }
  2459.  
  2460. /* This return 0 if the given file entry's symbol table does *not*
  2461.    contain the nlist point entry, and it returns the files entry
  2462.    pointer (cast to unsigned long) if it does. */
  2463.  
  2464. unsigned long
  2465. contains_symbol (entry, n_ptr)
  2466.      struct file_entry *entry;
  2467.      register struct nlist *n_ptr;
  2468. {
  2469.   if (n_ptr >= entry->symbols &&
  2470.       n_ptr < (entry->symbols
  2471.            + (entry->syms_size / sizeof (struct nlist))))
  2472.     return (unsigned long) entry;
  2473.   return 0;
  2474. }
  2475.  
  2476.  
  2477. /* Searching libraries */
  2478.  
  2479. struct file_entry *decode_library_subfile ();
  2480. void linear_library (), symdef_library ();
  2481.  
  2482. /* Search the library ENTRY, already open on descriptor DESC.
  2483.    This means deciding which library members to load,
  2484.    making a chain of `struct file_entry' for those members,
  2485.    and entering their global symbols in the hash table.  */
  2486.  
  2487. void
  2488. search_library (desc, entry)
  2489.      int desc;
  2490.      struct file_entry *entry;
  2491. {
  2492.   int member_length;
  2493.   register char *name;
  2494.   register struct file_entry *subentry;
  2495.  
  2496.   if (!undefined_global_sym_count) return;
  2497.  
  2498.   /* Examine its first member, which starts SARMAG bytes in.  */
  2499.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2500.   if (!subentry) return;
  2501.  
  2502.   name = subentry->filename;
  2503.   free (subentry);
  2504.  
  2505.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2506.  
  2507.   if (!strcmp (name, "__.SYMDEF"))
  2508.     symdef_library (desc, entry, member_length);
  2509.   else
  2510.     linear_library (desc, entry);
  2511. }
  2512.  
  2513. /* Construct and return a file_entry for a library member.
  2514.    The library's file_entry is library_entry, and the library is open on DESC.
  2515.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2516.    We store the length of the member into *LENGTH_LOC.  */
  2517.  
  2518. struct file_entry *
  2519. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2520.      int desc;
  2521.      struct file_entry *library_entry;
  2522.      int subfile_offset;
  2523.      int *length_loc;
  2524. {
  2525.   int bytes_read;
  2526.   register int namelen;
  2527.   int member_length;
  2528.   register char *name;
  2529.   struct ar_hdr hdr1;
  2530.   register struct file_entry *subentry;
  2531.  
  2532.   lseek (desc, subfile_offset, 0);
  2533.  
  2534.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2535.   if (!bytes_read)
  2536.     return 0;        /* end of archive */
  2537.  
  2538.   if (sizeof hdr1 != bytes_read)
  2539.     fatal_with_file ("malformed library archive ", library_entry);
  2540.  
  2541.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2542.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2543.  
  2544.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2545.   bzero (subentry, sizeof (struct file_entry));
  2546.  
  2547.   for (namelen = 0;
  2548.        namelen < sizeof hdr1.ar_name
  2549.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2550.        && hdr1.ar_name[namelen] != '/';
  2551.        namelen++);
  2552.  
  2553.   name = (char *) xmalloc (namelen+1);
  2554.   strncpy (name, hdr1.ar_name, namelen);
  2555.   name[namelen] = 0;
  2556.  
  2557.   subentry->filename = name;
  2558.   subentry->local_sym_name = name;
  2559.   subentry->symbols = 0;
  2560.   subentry->strings = 0;
  2561.   subentry->subfiles = 0;
  2562.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2563.   subentry->superfile = library_entry;
  2564.   subentry->library_flag = 0;
  2565.   subentry->header_read_flag = 0;
  2566.   subentry->just_syms_flag = 0;
  2567.   subentry->chain = 0;
  2568.   subentry->total_size = member_length;
  2569.  
  2570.   (*length_loc) = member_length;
  2571.  
  2572.   return subentry;
  2573. }
  2574.  
  2575. int subfile_wanted_p ();
  2576.  
  2577. /* Search a library that has a __.SYMDEF member.
  2578.    DESC is a descriptor on which the library is open.
  2579.      The file pointer is assumed to point at the __.SYMDEF data.
  2580.    ENTRY is the library's file_entry.
  2581.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2582.  
  2583. void
  2584. symdef_library (desc, entry, member_length)
  2585.      int desc;
  2586.      struct file_entry *entry;
  2587.      int member_length;
  2588. {
  2589.   int *symdef_data = (int *) xmalloc (member_length);
  2590.   register struct symdef *symdef_base;
  2591.   char *sym_name_base;
  2592.   int number_of_symdefs;
  2593.   int length_of_strings;
  2594.   int not_finished;
  2595.   int bytes_read;
  2596.   register int i;
  2597.   struct file_entry *prev = 0;
  2598.   int prev_offset = 0;
  2599.  
  2600.   bytes_read = read (desc, symdef_data, member_length);
  2601.   if (bytes_read != member_length)
  2602.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2603.  
  2604.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2605.   if (number_of_symdefs < 0 ||
  2606.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2607.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2608.  
  2609.   symdef_base = (struct symdef *) (symdef_data + 1);
  2610.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2611.  
  2612.   if (length_of_strings < 0
  2613.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2614.       + 2 * sizeof (int) != member_length)
  2615.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2616.  
  2617.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2618.  
  2619.   /* Check all the string indexes for validity.  */
  2620.  
  2621.   for (i = 0; i < number_of_symdefs; i++)
  2622.     {
  2623.       register int index = symdef_base[i].symbol_name_string_index;
  2624.       if (index < 0 || index >= length_of_strings
  2625.       || (index && *(sym_name_base + index - 1)))
  2626.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2627.     }
  2628.  
  2629.   /* Search the symdef data for members to load.
  2630.      Do this until one whole pass finds nothing to load.  */
  2631.  
  2632.   not_finished = 1;
  2633.   while (not_finished)
  2634.     {
  2635.       not_finished = 0;
  2636.  
  2637.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2638.      Load the library members that contain such symbols.  */
  2639.  
  2640.       for (i = 0;
  2641.        (i < number_of_symdefs
  2642.         && (undefined_global_sym_count || common_defined_global_count));
  2643.        i++)
  2644.     if (symdef_base[i].symbol_name_string_index >= 0)
  2645.       {
  2646.         register symbol *sp;
  2647.  
  2648.         sp = getsym_soft (sym_name_base
  2649.                   + symdef_base[i].symbol_name_string_index);
  2650.  
  2651.         /* If we find a symbol that appears to be needed, think carefully
  2652.            about the archive member that the symbol is in.  */
  2653.  
  2654.         if (sp && ((sp->referenced && !sp->defined)
  2655.                || (sp->defined && sp->max_common_size)))
  2656.           {
  2657.         int junk;
  2658.         register int j;
  2659.         register int offset = symdef_base[i].library_member_offset;
  2660.         struct file_entry *subentry;
  2661.  
  2662.         /* Don't think carefully about any archive member
  2663.            more than once in a given pass.  */
  2664.  
  2665.         if (prev_offset == offset)
  2666.           continue;
  2667.         prev_offset = offset;
  2668.  
  2669.         /* Read the symbol table of the archive member.  */
  2670.  
  2671.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2672.         if (subentry == 0)
  2673.           fatal ("invalid offset for %s in symbol table of %s",
  2674.              sym_name_base
  2675.              + symdef_base[i].symbol_name_string_index,
  2676.              entry->filename);
  2677.         read_entry_symbols (desc, subentry);
  2678.         subentry->strings = xmalloc (subentry->strs_size);
  2679.         read_entry_strings (desc, subentry);
  2680.  
  2681.         /* Now scan the symbol table and decide whether to load.  */
  2682.  
  2683.         if (!subfile_wanted_p (subentry))
  2684.           {
  2685.             free (subentry->symbols);
  2686.             free (subentry->strings);
  2687.             free (subentry);
  2688.           }
  2689.         else
  2690.           {
  2691.             /* This member is needed; load it.
  2692.                Since we are loading something on this pass,
  2693.                we must make another pass through the symdef data.  */
  2694.  
  2695.             not_finished = 1;
  2696.  
  2697.             enter_file_symbols (subentry);
  2698.  
  2699.             if (prev)
  2700.               prev->chain = subentry;
  2701.             else entry->subfiles = subentry;
  2702.             prev = subentry;
  2703.  
  2704.             /* Clear out this member's symbols from the symdef data
  2705.                so that following passes won't waste time on them.  */
  2706.  
  2707.             for (j = 0; j < number_of_symdefs; j++)
  2708.               {
  2709.             if (symdef_base[j].library_member_offset == offset)
  2710.               symdef_base[j].symbol_name_string_index = -1;
  2711.               }
  2712.  
  2713.             /* We'll read the strings again if we need them again.  */
  2714.             free (subentry->strings);
  2715.             subentry->strings = 0;
  2716.           }
  2717.           }
  2718.       }
  2719.     }
  2720.  
  2721.   free (symdef_data);
  2722. }
  2723.  
  2724.  
  2725. /* Handle a subentry for a file with no __.SYMDEF. */
  2726.  
  2727. process_subentry (desc, subentry, entry, prev_addr)
  2728.      int desc;
  2729.      register struct file_entry *subentry;
  2730.      struct file_entry **prev_addr, *entry;
  2731. {
  2732.   read_entry_symbols (desc, subentry);
  2733.   subentry->strings = (char *) alloca (subentry->strs_size);
  2734.   read_entry_strings (desc, subentry);
  2735.  
  2736.   if (!subfile_wanted_p (subentry))
  2737.     {
  2738.       free (subentry->symbols);
  2739.       free (subentry);
  2740.     }
  2741.   else
  2742.     {
  2743.       enter_file_symbols (subentry);
  2744.  
  2745.       if (*prev_addr)
  2746.     (*prev_addr)->chain = subentry;
  2747.       else
  2748.     entry->subfiles = subentry;
  2749.       *prev_addr = subentry;
  2750.       subentry->strings = 0; /* Since space will dissapear on return */
  2751.     }
  2752. }
  2753.  
  2754. /* Search a library that has no __.SYMDEF.
  2755.    ENTRY is the library's file_entry.
  2756.    DESC is the descriptor it is open on.  */
  2757.  
  2758. void
  2759. linear_library (desc, entry)
  2760.      int desc;
  2761.      struct file_entry *entry;
  2762. {
  2763.   struct file_entry *prev = 0;
  2764.   register int this_subfile_offset = SARMAG;
  2765.  
  2766.   while (undefined_global_sym_count || common_defined_global_count)
  2767.     {
  2768.       int member_length;
  2769.       register struct file_entry *subentry;
  2770.  
  2771.       subentry = decode_library_subfile (desc, entry, this_subfile_offset,
  2772.                      &member_length);
  2773.       if (!subentry) return;
  2774.  
  2775.       process_subentry (desc, subentry, entry, &prev);
  2776.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2777.       if (this_subfile_offset & 1) this_subfile_offset++;
  2778.     }
  2779. }
  2780.  
  2781. /* ENTRY is an entry for a library member.
  2782.    Its symbols have been read into core, but not entered.
  2783.    Return nonzero if we ought to load this member.  */
  2784.  
  2785. int
  2786. subfile_wanted_p (entry)
  2787.      struct file_entry *entry;
  2788. {
  2789.   register struct nlist *p;
  2790.   register struct nlist *end
  2791.     = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2792. #ifdef DOLLAR_KLUDGE
  2793.   register int dollar_cond = 0;
  2794. #endif
  2795.  
  2796.   for (p = entry->symbols; p < end; p++)
  2797.     {
  2798.       register int type = p->n_type;
  2799.       register char *name = p->n_un.n_strx + entry->strings;
  2800.  
  2801.       /* If the symbol has an interesting definition, we could
  2802.      potentially want it.  */
  2803.       if (type & N_EXT
  2804.       && (type != (N_UNDF | N_EXT) || p->n_value
  2805.  
  2806. #ifdef DOLLAR_KLUDGE
  2807.            || name[1] == '$'
  2808. #endif
  2809.           )
  2810.       && !SET_ELEMENT_P (type)
  2811.       && !set_element_prefixed_p (name))
  2812.     {
  2813.       register symbol *sp = getsym_soft (name);
  2814.  
  2815. #ifdef DOLLAR_KLUDGE
  2816.       if (name[1] == '$')
  2817.         {
  2818.           sp = getsym_soft (&name[2]);
  2819.           dollar_cond = 1;
  2820.           if (!sp) continue;
  2821.           if (sp->referenced)
  2822.         {
  2823.           if (write_map)
  2824.             {
  2825.               print_file_name (entry, stdout);
  2826.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2827.             }
  2828.           return 1;
  2829.         }
  2830.           continue;
  2831.         }
  2832. #endif
  2833.  
  2834.       /* If this symbol has not been hashed, we can't be looking for it. */
  2835.  
  2836.       if (!sp) continue;
  2837.  
  2838.       if ((sp->referenced && !sp->defined)
  2839.           /* NB.  This needs to be changed so that, e.g., "int pipe;" won't import
  2840.          pipe() from the library.  But the bug fix kingdon made was wrong.  */
  2841.           || (sp->defined && sp->max_common_size))
  2842.         {
  2843.           /* This is a symbol we are looking for.  It is either
  2844.              not yet defined or defined as a common.  */
  2845. #ifdef DOLLAR_KLUDGE
  2846.           if (dollar_cond) continue;
  2847. #endif
  2848.           if (type == (N_UNDF | N_EXT))
  2849.         {
  2850.           /* Symbol being defined as common.
  2851.              Remember this, but don't load subfile just for this.  */
  2852.  
  2853.           /* If it didn't used to be common, up the count of
  2854.              common symbols.  */
  2855.           if (!sp->max_common_size)
  2856.             common_defined_global_count++;
  2857.  
  2858.           if (sp->max_common_size < p->n_value)
  2859.             sp->max_common_size = p->n_value;
  2860.           if (!sp->defined)
  2861.             undefined_global_sym_count--;
  2862.           sp->defined = 1;
  2863.           continue;
  2864.         }
  2865.  
  2866.           if (write_map)
  2867.         {
  2868.           print_file_name (entry, stdout);
  2869.           fprintf (stdout, " needed due to %s\n", sp->name);
  2870.         }
  2871.           return 1;
  2872.         }
  2873.     }
  2874.     }
  2875.  
  2876.   return 0;
  2877. }
  2878.  
  2879. void consider_file_section_lengths (), relocate_file_addresses ();
  2880.  
  2881. /* Having entered all the global symbols and found the sizes of sections
  2882.    of all files to be linked, make all appropriate deductions from this data.
  2883.  
  2884.    We propagate global symbol values from definitions to references.
  2885.    We compute the layout of the output file and where each input file's
  2886.    contents fit into it.  */
  2887.  
  2888. void
  2889. digest_symbols ()
  2890. {
  2891.   register int i;
  2892.   int setv_fill_count;
  2893.  
  2894.   if (trace_files)
  2895.     fprintf (stderr, "Digesting symbol information:\n\n");
  2896.  
  2897.   /* Initialize the text_start address; this depends on the output file formats.  */
  2898.  
  2899.   initialize_text_start ();
  2900.  
  2901. #ifdef HUNK_INSTEAD_OF_A_OUT
  2902.   text_size = 0;
  2903. #else
  2904.   text_size = text_header_size;
  2905. #endif
  2906.  
  2907.   /* Compute total size of sections */
  2908.  
  2909.   each_file (consider_file_section_lengths, 0);
  2910.  
  2911.   /* If necessary, pad text section to full page in the file.
  2912.      Include the padding in the text segment size.  */
  2913.  
  2914. #ifndef HUNK_INSTEAD_OF_A_OUT
  2915.   if (output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  2916.     {
  2917.       text_pad = ((text_size + page_size - 1) & (- page_size)) - text_size;
  2918.       text_size += text_pad;
  2919.     }
  2920. #endif
  2921.  
  2922. #ifdef HUNK_INSTEAD_OF_A_OUT
  2923.   /* they go into text if they are required */
  2924.   if (output_datadata_relocs && numdatadata_relocs)
  2925.     {
  2926.       if (datadata_reloc_symbol)
  2927.         datadata_reloc_symbol->value = text_size;
  2928.       
  2929.       /* 1 long for the size, then the vector */
  2930.       text_size += (1 + numdatadata_relocs) * 4;
  2931.     }
  2932. #endif
  2933.  
  2934.   /* Now that the text_size is known, initialize the data start address;
  2935.      this depends on text_size as well as the output file format.  */
  2936.  
  2937.   initialize_data_start ();
  2938.  
  2939. #ifdef HUNK_INSTEAD_OF_A_OUT
  2940.   data_pad = 0;
  2941. #endif
  2942.  
  2943.  
  2944. #ifndef HUNK_INSTEAD_OF_A_OUT
  2945.   /* Make sure bss starts out aligned as much as anyone can want.  */
  2946.   {
  2947.     int new_data_size = (data_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  2948.  
  2949.     data_pad += new_data_size - data_size;
  2950.     data_size = new_data_size;
  2951.   }
  2952. #endif
  2953.  
  2954.   /* Set up the set element vector */
  2955.  
  2956.   if (output_style != OUTPUT_RELOCATABLE)
  2957.     {
  2958.       /* The set sector size is the number of set elements + a word
  2959.          for each symbol for the length word at the beginning of the
  2960.      vector, plus a word for each symbol for a zero at the end of
  2961.      the vector (for incremental linking).  */
  2962. #if 0
  2963.       /* I think this is the other way round !? ### mw */
  2964.  
  2965.       set_sect_size
  2966.     = (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  2967. #else
  2968.       set_sect_size
  2969.     = (2 * set_vector_count + set_symbol_count) * sizeof (unsigned long);
  2970. #endif
  2971.       set_sect_start = data_start + data_size;
  2972.       data_size += set_sect_size;
  2973.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  2974.       setv_fill_count = 0;
  2975.     }
  2976.  
  2977.   /* Compute start addresses of each file's sections and symbols.  */
  2978.  
  2979.   each_full_file (relocate_file_addresses, 0);
  2980.  
  2981.   /* Now, for each symbol, verify that it is defined globally at most once.
  2982.      Put the global value into the symbol entry.
  2983.      Common symbols are allocated here, in the BSS section.
  2984.      Each defined symbol is given a '->defined' field
  2985.       which is the correct N_ code for its definition,
  2986.       except in the case of common symbols with -r.
  2987.      Then make all the references point at the symbol entry
  2988.      instead of being chained together. */
  2989.  
  2990.   defined_global_sym_count = 0;
  2991.  
  2992.   for (i = 0; i < TABSIZE; i++)
  2993.     {
  2994.       register symbol *sp;
  2995.       for (sp = symtab[i]; sp; sp = sp->link)
  2996.     {
  2997.       /* For each symbol */
  2998.       register struct nlist *p, *next;
  2999.       int defs = 0, com = sp->max_common_size;
  3000.       struct nlist *first_definition;
  3001.       for (p = sp->refs; p; p = next)
  3002.         {
  3003.           register int type = p->n_type;
  3004.  
  3005.           if (SET_ELEMENT_P (type))
  3006.         {
  3007.           if (output_style == OUTPUT_RELOCATABLE)
  3008.             fatal ("internal: global ref to set element with -r");
  3009.           if (!defs++)
  3010.             {
  3011.               sp->value = set_sect_start
  3012.             + setv_fill_count++ * sizeof (unsigned long);
  3013.               sp->defined = N_SETV | N_EXT;
  3014.               first_definition = p;
  3015.             }
  3016.           else if ((sp->defined & ~N_EXT) != N_SETV)
  3017.             {
  3018.               sp->multiply_defined = 1;
  3019.               multiple_def_count++;
  3020.             }
  3021.           set_vectors[setv_fill_count++] = p->n_value;
  3022.         }
  3023.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  3024.         {
  3025.           /* non-common definition */
  3026.           if (defs++ && sp->value != p->n_value)
  3027.             {
  3028.               sp->multiply_defined = 1;
  3029.               multiple_def_count++;
  3030.             }
  3031.           sp->value = p->n_value;
  3032.           sp->defined = type;
  3033.           first_definition = p;
  3034.         }
  3035.           next = (struct nlist *) p->n_un.n_name;
  3036.           p->n_un.n_name = (char *) sp;
  3037.         }
  3038.       /* Allocate as common if defined as common and not defined for real */
  3039.       if (com && !defs)
  3040.         {
  3041.           if (output_style != OUTPUT_RELOCATABLE || force_common_definition)
  3042.         {
  3043.           int align = sizeof (int);
  3044.  
  3045.           /* Round up to nearest sizeof (int).  I don't know
  3046.              whether this is necessary or not (given that
  3047.              alignment is taken care of later), but it's
  3048.              traditional, so I'll leave it in.  Note that if
  3049.              this size alignment is ever removed, ALIGN above
  3050.              will have to be initialized to 1 instead of
  3051.              sizeof (int).  */
  3052.  
  3053.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  3054.  
  3055.           while (!(com & align))
  3056.             align <<= 1;
  3057.  
  3058.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  3059.  
  3060.           bss_size = ((((bss_size + data_size + data_start)
  3061.                   + (align - 1)) & (- align))
  3062.                   - data_size - data_start);
  3063.  
  3064. #ifdef HUNK_INSTEAD_OF_A_OUT
  3065.           sp->value = bss_size;
  3066.           if (databss_together)
  3067.             sp->value += data_start + data_size;
  3068. #else
  3069.           sp->value = data_start + data_size + bss_size;
  3070. #endif
  3071.           sp->defined = N_BSS | N_EXT;
  3072.           bss_size += com;
  3073.           if (write_map)
  3074.             printf ("Allocating common %s: %x at %x\n",
  3075.                 sp->name, com, sp->value);
  3076.         }
  3077.           else
  3078.         {
  3079.           sp->defined = 0;
  3080.           undefined_global_sym_count++;
  3081.         }
  3082.         }
  3083.       /* Set length word at front of vector and zero byte at end.
  3084.          Reverse the vector itself to put it in file order.  */
  3085.       if ((sp->defined & ~N_EXT) == N_SETV)
  3086.         {
  3087.           unsigned long length_word_index
  3088.         = (sp->value - set_sect_start) / sizeof (unsigned long);
  3089.           unsigned long i, tmp;
  3090.  
  3091.           set_vectors[length_word_index]
  3092.         = setv_fill_count - 1 - length_word_index;
  3093.  
  3094.           /* Reverse the vector.  */
  3095.           for (i = 1;
  3096.            i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  3097.            i++)
  3098.         {
  3099.           tmp = set_vectors[length_word_index + i];
  3100.           set_vectors[length_word_index + i]
  3101.             = set_vectors[setv_fill_count - i];
  3102.           set_vectors[setv_fill_count - i] = tmp;
  3103.         }
  3104.  
  3105.           set_vectors[setv_fill_count++] = 0;
  3106.         }
  3107.       if (sp->defined)
  3108.         defined_global_sym_count++;
  3109.     }
  3110.     }
  3111.  
  3112.   /* Make sure end of bss is aligned as much as anyone can want.  */
  3113.  
  3114.   bss_size = (bss_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3115.  
  3116.   /* Give values to _end and friends.  */
  3117.   {
  3118.     int end_value = data_start + data_size + bss_size;
  3119.     if (end_symbol)
  3120.       end_symbol->value = end_value;
  3121.     if (end_symbol_alt)
  3122.       end_symbol_alt->value = end_value;
  3123.   }
  3124.  
  3125.   {
  3126.     int etext_value = text_size + text_start;
  3127.     if (etext_symbol)
  3128.       etext_symbol->value = etext_value;
  3129.     if (etext_symbol_alt)
  3130.       etext_symbol_alt->value = etext_value;
  3131.   }
  3132.  
  3133. #ifdef amigados
  3134.   {
  3135.     if (sdata_symbol)
  3136.       sdata_symbol->value = data_start;
  3137.     if (text_size_symbol)
  3138.       text_size_symbol->value = text_size;
  3139.     if (data_size_symbol)
  3140.       data_size_symbol->value = data_size;
  3141.     if (bss_size_symbol)
  3142.       bss_size_symbol->value  = bss_size;
  3143.   }
  3144. #endif
  3145.  
  3146.   {
  3147.     int edata_value = data_start + data_size;
  3148.     if (edata_symbol)
  3149.       edata_symbol->value = edata_value;
  3150.     if (edata_symbol_alt)
  3151.       edata_symbol_alt->value = edata_value;
  3152.   }
  3153.  
  3154.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  3155.  
  3156.   {
  3157.     /* The amount of data_pad that we are computing now.  This is the
  3158.        part which overlaps with bss.  What was computed previously
  3159.        goes before bss.  */
  3160.     int data_pad_additional = 0;
  3161.     
  3162.     if (specified_data_size && specified_data_size > data_size)
  3163.       data_pad_additional = specified_data_size - data_size;
  3164.  
  3165. #ifndef HUNK_INSTEAD_OF_A_OUT
  3166.     if (output_style == OUTPUT_DEMAND_PAGED)
  3167.       data_pad_additional =
  3168.     ((data_pad_additional + data_size + page_size - 1) & (- page_size)) - data_size;
  3169. #endif
  3170.  
  3171.     bss_size -= data_pad_additional;
  3172.     if (bss_size < 0) bss_size = 0;
  3173.  
  3174.     data_size += data_pad_additional;
  3175.  
  3176.     data_pad += data_pad_additional;
  3177.   }
  3178.  
  3179. #ifdef HUNK_INSTEAD_OF_A_OUT
  3180.   /* if there is some code, assign it next hunk_number */
  3181.   if (text_size)
  3182.      number_of_code_hunk = current_hunk++;
  3183.   else
  3184.      number_of_code_hunk = -1;
  3185.  
  3186.   if (data_size)
  3187.      number_of_data_hunk = current_hunk++;
  3188.   else
  3189.      number_of_data_hunk = -1;
  3190.  
  3191.   if (bss_size)
  3192.      number_of_bss_hunk  = current_hunk++;
  3193.   else
  3194.      number_of_bss_hunk  = -1;
  3195.  
  3196.   if (databss_together)
  3197.     {
  3198.       if (data_size && bss_size)
  3199.     {
  3200.       current_hunk --;
  3201.       number_of_bss_hunk = number_of_data_hunk;
  3202.     }
  3203.     }
  3204.  
  3205.   if (strip_symbols != STRIP_ALL && !amiga_symbols_only)
  3206.      number_of_debug_hunk = current_hunk++;
  3207.   else
  3208.      number_of_debug_hunk = -1;
  3209. #endif
  3210. }
  3211.  
  3212. /* Accumulate the section sizes of input file ENTRY
  3213.    into the section sizes of the output file.  */
  3214.  
  3215. void
  3216. consider_file_section_lengths (entry)
  3217.      register struct file_entry *entry;
  3218. {
  3219.   if (entry->just_syms_flag)
  3220.     return;
  3221.  
  3222.   entry->text_start_address = text_size;
  3223.   /* If there were any vectors, we need to chop them off */
  3224.   text_size += entry->text_size;
  3225.   entry->data_start_address = data_size;
  3226.   data_size += entry->data_size;
  3227.   entry->bss_start_address = bss_size;
  3228.   bss_size += entry->bss_size;
  3229.  
  3230.   text_reloc_size += entry->text_reloc_size;
  3231.   data_reloc_size += entry->data_reloc_size;
  3232.  
  3233. #ifdef HUNK_INSTEAD_OF_A_OUT
  3234.   if (! output_datadata_relocs)
  3235.     return;
  3236.  
  3237.   /* have to guess at how many datadata-relocs we might have. This number
  3238.      is larger than the real thing, because I have to include the references
  3239.      to UNDF symbols as well. */
  3240.   {
  3241.     struct relocation_info *r, *re, *reloc;
  3242.     int desc = file_open (entry);
  3243.  
  3244.     reloc = (struct relocation_info *) alloca (entry->data_reloc_size);
  3245.     lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  3246.     if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  3247.       fatal_with_file ("premature eof in data relocation of ", entry);
  3248.     
  3249.     for (r = reloc, re = reloc + entry->data_reloc_size/sizeof(*re); r < re; r++)
  3250.       if (RELOC_EXTERN_P (r) || ((RELOC_TYPE (r) & N_TYPE) != N_TEXT))
  3251.     numdatadata_relocs ++;
  3252.  
  3253.     file_close ();
  3254.   }
  3255. #endif
  3256. }
  3257.  
  3258. /* Determine where the sections of ENTRY go into the output file,
  3259.    whose total section sizes are already known.
  3260.    Also relocate the addresses of the file's local and debugger symbols.  */
  3261.  
  3262. void
  3263. relocate_file_addresses (entry)
  3264.      register struct file_entry *entry;
  3265. {
  3266.   entry->text_start_address += text_start;
  3267.  
  3268.   /* Note that `data_start' and `data_size' have not yet been adjusted
  3269.      for the portion of data_pad which overlaps with bss.  If they had
  3270.      been, we would get the wrong results here.  */
  3271.   entry->data_start_address += data_start;
  3272.  
  3273. #ifdef HUNK_INSTEAD_OF_A_OUT
  3274.   if (databss_together)
  3275. #endif
  3276.     entry->bss_start_address += data_start + data_size;
  3277.  
  3278.  
  3279.   {
  3280.     register struct nlist *p;
  3281.     register struct nlist *end
  3282.       = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3283.  
  3284.     for (p = entry->symbols; p < end; p++)
  3285.       {
  3286.     /* If this belongs to a section, update it by the section's start address */
  3287.     register int type = p->n_type & N_TYPE;
  3288.  
  3289.     switch (type)
  3290.       {
  3291.       case N_TEXT:
  3292.       case N_SETT:
  3293.         p->n_value += entry->text_start_address - entry->orig_text_address;
  3294.         break;
  3295.       case N_SETV:
  3296.       case N_DATA:
  3297.       case N_SETD:
  3298.         /* Data segment symbol.  Subtract the address of the
  3299.            data segment in the input file, and add the address
  3300.            of this input file's data segment in the output file.  */
  3301.         p->n_value +=
  3302.           entry->data_start_address - entry->orig_data_address;
  3303.         break;
  3304.       case N_BSS:
  3305.       case N_SETB:
  3306.         /* likewise for symbols with value in BSS.  */
  3307.         p->n_value += entry->bss_start_address - entry->orig_bss_address;
  3308.         break;
  3309.       }
  3310.       }
  3311.   }
  3312. }
  3313.  
  3314. void describe_file_sections (), list_file_locals ();
  3315.  
  3316. /* Print a complete or partial map of the output file.  */
  3317.  
  3318. void
  3319. print_symbols (outfile)
  3320.      FILE *outfile;
  3321. {
  3322.   register int i;
  3323.  
  3324.   fprintf (outfile, "\nFiles:\n\n");
  3325.  
  3326.   each_file (describe_file_sections, outfile);
  3327.  
  3328.   fprintf (outfile, "\nGlobal symbols:\n\n");
  3329.  
  3330.   for (i = 0; i < TABSIZE; i++)
  3331.     {
  3332.       register symbol *sp;
  3333.       for (sp = symtab[i]; sp; sp = sp->link)
  3334.     {
  3335.       if (sp->defined == 1)
  3336.         fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
  3337.       if (sp->defined)
  3338.         fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
  3339.       else if (sp->referenced)
  3340.         fprintf (outfile, "  %s: undefined\n", sp->name);
  3341.     }
  3342.     }
  3343.  
  3344.   each_file (list_file_locals, outfile);
  3345. }
  3346.  
  3347. void
  3348. describe_file_sections (entry, outfile)
  3349.      struct file_entry *entry;
  3350.      FILE *outfile;
  3351. {
  3352.   fprintf (outfile, "  ");
  3353.   print_file_name (entry, outfile);
  3354.   if (entry->just_syms_flag)
  3355.     fprintf (outfile, " symbols only\n", 0);
  3356.   else
  3357.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  3358.          entry->text_start_address, entry->text_size,
  3359.          entry->data_start_address, entry->data_size,
  3360.          entry->bss_start_address, entry->bss_size);
  3361. }
  3362.  
  3363. void
  3364. list_file_locals (entry, outfile)
  3365.      struct file_entry *entry;
  3366.      FILE *outfile;
  3367. {
  3368.   register struct nlist
  3369.     *p,
  3370.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3371.  
  3372.   entry->strings = (char *) alloca (entry->strs_size);
  3373.   read_entry_strings (file_open (entry), entry);
  3374.  
  3375.   fprintf (outfile, "\nLocal symbols of ");
  3376.   print_file_name (entry, outfile);
  3377.   fprintf (outfile, ":\n\n");
  3378.  
  3379.   for (p = entry->symbols; p < end; p++)
  3380.     /* If this is a definition,
  3381.        update it if necessary by this file's start address.  */
  3382.     if (!(p->n_type & (N_STAB | N_EXT)))
  3383.       fprintf (outfile, "  %s: 0x%x\n",
  3384.            entry->strings + p->n_un.n_strx, p->n_value);
  3385.  
  3386.   entry->strings = 0;        /* All done with them.  */
  3387. }
  3388.  
  3389.  
  3390. /* Static vars for do_warnings and subroutines of it */
  3391. int list_unresolved_refs;    /* List unresolved refs */
  3392. int list_warning_symbols;    /* List warning syms */
  3393. int list_multiple_defs;        /* List multiple definitions */
  3394.  
  3395. /*
  3396.  * Structure for communication between do_file_warnings and it's
  3397.  * helper routines.  Will in practice be an array of three of these:
  3398.  * 0) Current line, 1) Next line, 2) Source file info.
  3399.  */
  3400. struct line_debug_entry
  3401. {
  3402.   int line;
  3403.   char *filename;
  3404.   struct nlist *sym;
  3405. };
  3406.  
  3407. void qsort ();
  3408. /*
  3409.  * Helper routines for do_file_warnings.
  3410.  */
  3411.  
  3412. /* Return an integer less than, equal to, or greater than 0 as per the
  3413.    relation between the two relocation entries.  Used by qsort.  */
  3414.  
  3415. int
  3416. relocation_entries_relation (rel1, rel2)
  3417.      struct relocation_info *rel1, *rel2;
  3418. {
  3419.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  3420. }
  3421.  
  3422. /* Moves to the next debugging symbol in the file.  USE_DATA_SYMBOLS
  3423.    determines the type of the debugging symbol to look for (DSLINE or
  3424.    SLINE).  STATE_POINTER keeps track of the old and new locatiosn in
  3425.    the file.  It assumes that state_pointer[1] is valid; ie
  3426.    that it.sym points into some entry in the symbol table.  If
  3427.    state_pointer[1].sym == 0, this routine should not be called.  */
  3428.  
  3429. int
  3430. next_debug_entry (use_data_symbols, state_pointer)
  3431.      register int use_data_symbols;
  3432.      /* Next must be passed by reference! */
  3433.      struct line_debug_entry state_pointer[3];
  3434. {
  3435.   register struct line_debug_entry
  3436.     *current = state_pointer,
  3437.     *next = state_pointer + 1,
  3438.     /* Used to store source file */
  3439.     *source = state_pointer + 2;
  3440.   struct file_entry *entry = (struct file_entry *) source->sym;
  3441.  
  3442.   current->sym = next->sym;
  3443.   current->line = next->line;
  3444.   current->filename = next->filename;
  3445.  
  3446.   while (++(next->sym) < (entry->symbols
  3447.               + entry->syms_size/sizeof (struct nlist)))
  3448.     {
  3449.       /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
  3450.        * may look negative...therefore, must mask to low bits
  3451.        */
  3452.       switch (next->sym->n_type & 0xff)
  3453.     {
  3454.     case N_SLINE:
  3455.       if (use_data_symbols) continue;
  3456.       next->line = next->sym->n_desc;
  3457.       return 1;
  3458.     case N_DSLINE:
  3459.       if (!use_data_symbols) continue;
  3460.       next->line = next->sym->n_desc;
  3461.       return 1;
  3462. #ifdef HAVE_SUN_STABS
  3463.     case N_EINCL:
  3464.       next->filename = source->filename;
  3465.       continue;
  3466. #endif
  3467.     case N_SO:
  3468.       source->filename = next->sym->n_un.n_strx + entry->strings;
  3469.       source->line++;
  3470. #ifdef HAVE_SUN_STABS
  3471.     case N_BINCL:
  3472. #endif
  3473.     case N_SOL:
  3474.       next->filename
  3475.         = next->sym->n_un.n_strx + entry->strings;
  3476.     default:
  3477.       continue;
  3478.     }
  3479.     }
  3480.   next->sym = (struct nlist *) 0;
  3481.   return 0;
  3482. }
  3483.  
  3484. /* Create a structure to save the state of a scan through the debug
  3485.    symbols.  USE_DATA_SYMBOLS is set if we should be scanning for
  3486.    DSLINE's instead of SLINE's.  entry is the file entry which points
  3487.    at the symbols to use.  */
  3488.  
  3489. struct line_debug_entry *
  3490. init_debug_scan (use_data_symbols, entry)
  3491.      int use_data_symbols;
  3492.      struct file_entry *entry;
  3493. {
  3494.   struct line_debug_entry
  3495.     *state_pointer
  3496.       = (struct line_debug_entry *)
  3497.     xmalloc (3 * sizeof (struct line_debug_entry));
  3498.   register struct line_debug_entry
  3499.     *current = state_pointer,
  3500.     *next = state_pointer + 1,
  3501.     *source = state_pointer + 2; /* Used to store source file */
  3502.  
  3503.   struct nlist *tmp;
  3504.  
  3505.   for (tmp = entry->symbols;
  3506.        tmp < (entry->symbols
  3507.           + entry->syms_size/sizeof (struct nlist));
  3508.        tmp++)
  3509.     if (tmp->n_type == (int) N_SO)
  3510.       break;
  3511.  
  3512.   if (tmp >= (entry->symbols
  3513.           + entry->syms_size/sizeof (struct nlist)))
  3514.     {
  3515.       /* I believe this translates to "We lose" */
  3516.       current->filename = next->filename = entry->filename;
  3517.       current->line = next->line = -1;
  3518.       current->sym = next->sym = (struct nlist *) 0;
  3519.       return state_pointer;
  3520.     }
  3521.  
  3522.   next->line = source->line = 0;
  3523.   next->filename = source->filename
  3524.     = (tmp->n_un.n_strx + entry->strings);
  3525.   source->sym = (struct nlist *) entry;
  3526.   next->sym = tmp;
  3527.  
  3528.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  3529.  
  3530.   if (!next->sym)        /* No line numbers for this section; */
  3531.                 /* setup output results as appropriate */
  3532.     {
  3533.       if (source->line)
  3534.     {
  3535.       current->filename = source->filename = entry->filename;
  3536.       current->line = -1;    /* Don't print lineno */
  3537.     }
  3538.       else
  3539.     {
  3540.       current->filename = source->filename;
  3541.       current->line = 0;
  3542.     }
  3543.       return state_pointer;
  3544.     }
  3545.  
  3546.  
  3547.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  3548.  
  3549.   return state_pointer;
  3550. }
  3551.  
  3552. /* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
  3553.    which describes the current location in the implied scan through
  3554.    the debug symbols within the file which ADDRESS is within, and
  3555.    returns the source line number which corresponds to ADDRESS.  */
  3556.  
  3557. int
  3558. address_to_line (address, state_pointer)
  3559.      unsigned long address;
  3560.      /* Next must be passed by reference! */
  3561.      struct line_debug_entry state_pointer[3];
  3562. {
  3563.   struct line_debug_entry
  3564.     *current = state_pointer,
  3565.     *next = state_pointer + 1;
  3566.   struct line_debug_entry *tmp_pointer;
  3567.  
  3568.   int use_data_symbols;
  3569.  
  3570.   if (next->sym)
  3571.     use_data_symbols = (next->sym->n_type & ~N_EXT) == N_DATA;
  3572.   else
  3573.     return current->line;
  3574.  
  3575.   /* Go back to the beginning if we've already passed it.  */
  3576.   if (current->sym->n_value > address)
  3577.     {
  3578.       tmp_pointer = init_debug_scan (use_data_symbols,
  3579.                      (struct file_entry *)
  3580.                      ((state_pointer + 2)->sym));
  3581.       state_pointer[0] = tmp_pointer[0];
  3582.       state_pointer[1] = tmp_pointer[1];
  3583.       state_pointer[2] = tmp_pointer[2];
  3584.       free (tmp_pointer);
  3585.     }
  3586.  
  3587.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3588.   if (current->sym->n_value > address)
  3589.     return -1;
  3590.  
  3591.   while (next->sym
  3592.      && next->sym->n_value <= address
  3593.      && next_debug_entry (use_data_symbols, state_pointer))
  3594.     ;
  3595.   return current->line;
  3596. }
  3597.  
  3598.  
  3599. /* Macros for manipulating bitvectors.  */
  3600. #define    BIT_SET_P(bv, index)    ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
  3601. #define    SET_BIT(bv, index)    ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
  3602.  
  3603. /* This routine will scan through the relocation data of file ENTRY,
  3604.    printing out references to undefined symbols and references to
  3605.    symbols defined in files with N_WARNING symbols.  If DATA_SEGMENT
  3606.    is non-zero, it will scan the data relocation segment (and use
  3607.    N_DSLINE symbols to track line number); otherwise it will scan the
  3608.    text relocation segment.  Warnings will be printed on the output
  3609.    stream OUTFILE.  Eventually, every nlist symbol mapped through will
  3610.    be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
  3611.    we scan the nlists themselves.  */
  3612.  
  3613. do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
  3614.      struct file_entry *entry;
  3615.      int data_segment;
  3616.      FILE *outfile;
  3617.      unsigned char *nlist_bitvector;
  3618. {
  3619.   struct relocation_info
  3620.     *reloc_start = data_segment ? entry->datarel : entry->textrel,
  3621.     *reloc;
  3622.   int reloc_size
  3623.     = ((data_segment ? entry->data_reloc_size : entry->text_reloc_size)
  3624.        / sizeof (struct relocation_info));
  3625.   int start_of_segment
  3626.     = (data_segment ? entry->data_start_address : entry->text_start_address);
  3627.   struct nlist *start_of_syms = entry->symbols;
  3628.   struct line_debug_entry *state_pointer
  3629.     = init_debug_scan (data_segment != 0, entry);
  3630.   register struct line_debug_entry *current = state_pointer;
  3631.   /* Assigned to generally static values; should not be written into.  */
  3632.   char *errfmt;
  3633.   /* Assigned to alloca'd values cand copied into; should be freed
  3634.      when done.  */
  3635.   char *errmsg;
  3636.   int invalidate_line_number;
  3637.  
  3638.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3639.      for one lousy error optimization. */
  3640.  
  3641.   qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
  3642.      relocation_entries_relation);
  3643.  
  3644.   for (reloc = reloc_start;
  3645.        reloc < (reloc_start + reloc_size);
  3646.        reloc++)
  3647.     {
  3648.       register struct nlist *s;
  3649.       register symbol *g;
  3650.  
  3651.       /* If the relocation isn't resolved through a symbol, continue */
  3652.       if (!RELOC_EXTERN_P(reloc))
  3653.     continue;
  3654.  
  3655.       s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
  3656.  
  3657.       /* Local symbols shouldn't ever be used by relocation info, so
  3658.      the next should be safe.
  3659.      This is, of course, wrong.  References to local BSS symbols can be
  3660.      the targets of relocation info, and they can (must) be
  3661.      resolved through symbols.  However, these must be defined properly,
  3662.      (the assembler would have caught it otherwise), so we can
  3663.      ignore these cases.  */
  3664.       if (!(s->n_type & N_EXT))
  3665.     continue;
  3666.  
  3667.       g = (symbol *) s->n_un.n_name;
  3668.       errmsg = 0;
  3669.  
  3670.       if (!g->defined && list_unresolved_refs) /* Reference */
  3671.     {
  3672.       /* Mark as being noted by relocation warning pass.  */
  3673.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3674.  
  3675.       if (g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3676.         continue;
  3677.  
  3678.       /* Undefined symbol which we should mention */
  3679.  
  3680.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3681.         {
  3682.           errfmt = "More undefined symbol %s refs follow";
  3683.           invalidate_line_number = 1;
  3684.         }
  3685.       else
  3686.         {
  3687.           errfmt = "Undefined symbol %s referenced from %s segment";
  3688.           invalidate_line_number = 0;
  3689.         }
  3690.     }
  3691.       else                         /* Defined */
  3692.     {
  3693.       /* Potential symbol warning here */
  3694.       if (!g->warning) continue;
  3695.  
  3696.       /* Mark as being noted by relocation warning pass.  */
  3697.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3698.  
  3699.       errfmt = 0;
  3700.       errmsg = g->warning;
  3701.       invalidate_line_number = 0;
  3702.     }
  3703.  
  3704.  
  3705.       /* If errfmt == 0, errmsg has already been defined.  */
  3706.       if (errfmt != 0)
  3707.     {
  3708.       char *nm;
  3709.  
  3710.       if (!demangler || !(nm = (*demangler)(g->name)))
  3711.         nm = g->name;
  3712.       errmsg = xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3713.       sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
  3714.       if (nm != g->name)
  3715.         free (nm);
  3716.     }
  3717.  
  3718.       address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
  3719.                state_pointer);
  3720.  
  3721.       if (current->line >=0)
  3722.     {
  3723.       fprintf (outfile, "%s:%d (", current->filename,
  3724.            invalidate_line_number ? 0 : current->line);
  3725.       print_file_name (entry, outfile);
  3726.       fprintf (outfile, "): %s\n", errmsg);
  3727.     }
  3728.       else
  3729.     {
  3730.       print_file_name(entry, outfile);
  3731.       fprintf(outfile, ": %s\n", errmsg);
  3732.     }
  3733.  
  3734.       if (errfmt != 0)
  3735.     free (errmsg);
  3736.     }
  3737.  
  3738.   free (state_pointer);
  3739. }
  3740.  
  3741. /* Print on OUTFILE a list of all warnings generated by references
  3742.    and/or definitions in the file ENTRY.  List source file and line
  3743.    number if possible, just the .o file if not. */
  3744.  
  3745. void
  3746. do_file_warnings (entry, outfile)
  3747.      struct file_entry *entry;
  3748.      FILE *outfile;
  3749. {
  3750.   int number_of_syms = entry->syms_size / sizeof (struct nlist);
  3751.   unsigned char *nlist_bitvector
  3752.     = (unsigned char *) alloca ((number_of_syms >> 3) + 1);
  3753.   struct line_debug_entry *text_scan, *data_scan;
  3754.   int i;
  3755.   char *errfmt, *file_name;
  3756.   int line_number;
  3757.   int dont_allow_symbol_name;
  3758.  
  3759.   bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
  3760.  
  3761.   /* Read in the files strings if they aren't available */
  3762.   if (!entry->strings)
  3763.     {
  3764.       int desc;
  3765.  
  3766.       entry->strings = (char *) alloca (entry->strs_size);
  3767.       desc = file_open (entry);
  3768.       read_entry_strings (desc, entry);
  3769.     }
  3770.  
  3771.   read_file_relocation (entry);
  3772.  
  3773.   /* Do text warnings based on a scan through the relocation info.  */
  3774.   do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
  3775.  
  3776.   /* Do data warnings based on a scan through the relocation info.  */
  3777.   do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
  3778.  
  3779.   /* Scan through all of the nlist entries in this file and pick up
  3780.      anything that the scan through the relocation stuff didn't.  */
  3781.  
  3782.   text_scan = init_debug_scan (0, entry);
  3783.   data_scan = init_debug_scan (1, entry);
  3784.  
  3785.   for (i = 0; i < number_of_syms; i++)
  3786.     {
  3787.       struct nlist *s;
  3788.       struct glosym *g;
  3789.  
  3790.       s = entry->symbols + i;
  3791.  
  3792.       if (!(s->n_type & N_EXT))
  3793.     continue;
  3794.  
  3795.       g = (symbol *) s->n_un.n_name;
  3796.       dont_allow_symbol_name = 0;
  3797.  
  3798.       if (list_multiple_defs && g->multiply_defined)
  3799.     {
  3800.       errfmt = "Definition of symbol %s (multiply defined)";
  3801.       switch (s->n_type)
  3802.         {
  3803.         case N_TEXT | N_EXT:
  3804.           line_number = address_to_line (s->n_value, text_scan);
  3805.           file_name = text_scan[0].filename;
  3806.           break;
  3807.         case N_DATA | N_EXT:
  3808.           line_number = address_to_line (s->n_value, data_scan);
  3809.           file_name = data_scan[0].filename;
  3810.           break;
  3811.         case N_SETA | N_EXT:
  3812.         case N_SETT | N_EXT:
  3813.         case N_SETD | N_EXT:
  3814.         case N_SETB | N_EXT:
  3815.           if (g->multiply_defined == 2)
  3816.         continue;
  3817.           errfmt = "First set element definition of symbol %s (multiply defined)";
  3818.           break;
  3819.         default:
  3820.           continue;        /* Don't print out multiple defs
  3821.                    at references.  */
  3822.         }
  3823.     }
  3824.       else if (BIT_SET_P (nlist_bitvector, i))
  3825.     continue;
  3826.       else if (list_unresolved_refs && !g->defined)
  3827.     {
  3828.       if (g->undef_refs >= MAX_UREFS_PRINTED)
  3829.         continue;
  3830.  
  3831.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3832.         errfmt = "More undefined \"%s\" refs follow";
  3833.       else
  3834.         errfmt = "Undefined symbol \"%s\" referenced";
  3835.       line_number = -1;
  3836.     }
  3837.       else if (g->warning)
  3838.     {
  3839.       /* There are two cases in which we don't want to
  3840.          do this.  The first is if this is a definition instead of
  3841.          a reference.  The second is if it's the reference used by
  3842.          the warning stabs itself.  */
  3843.       if (s->n_type != (N_EXT | N_UNDF)
  3844.           || (i && (s-1)->n_type == N_WARNING))
  3845.         continue;
  3846.  
  3847.       errfmt = g->warning;
  3848.       line_number = -1;
  3849.       dont_allow_symbol_name = 1;
  3850.     }
  3851.       else
  3852.     continue;
  3853.  
  3854.       if (line_number == -1)
  3855.     {
  3856.       print_file_name (entry, outfile);
  3857.       fprintf (outfile, ": ");
  3858.     }
  3859.       else
  3860.     {
  3861.       fprintf (outfile, "%s:%d (", file_name, line_number);
  3862.       print_file_name (entry, outfile);
  3863.       fprintf (outfile, "): ");
  3864.     }
  3865.  
  3866.       if (dont_allow_symbol_name)
  3867.     fprintf (outfile, "%s", errfmt);
  3868.       else
  3869.     {
  3870.       char *nm;
  3871.  
  3872.       if (!demangler || !(nm = (*demangler)(g->name)))
  3873.         fprintf (outfile, errfmt, g->name);
  3874.       else
  3875.         {
  3876.           fprintf (outfile, errfmt, nm);
  3877.           free (nm);
  3878.         }
  3879.     }
  3880.  
  3881.       fputc ('\n', outfile);
  3882.     }
  3883.   free (text_scan);
  3884.   free (data_scan);
  3885.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  3886. }
  3887.  
  3888. do_warnings (outfile)
  3889.      FILE *outfile;
  3890. {
  3891.   list_unresolved_refs = output_style != OUTPUT_RELOCATABLE && undefined_global_sym_count;
  3892.   list_warning_symbols = warning_count;
  3893.   list_multiple_defs = multiple_def_count != 0;
  3894.  
  3895.   if (!(list_unresolved_refs ||
  3896.     list_warning_symbols ||
  3897.     list_multiple_defs      ))
  3898.     /* No need to run this routine */
  3899.     return;
  3900.  
  3901.   each_file (do_file_warnings, outfile);
  3902.  
  3903.   if (list_unresolved_refs || list_multiple_defs)
  3904.     make_executable = 0;
  3905. }
  3906.  
  3907. #ifdef A_OUT
  3908.  
  3909. /* Stuff pertaining to creating a.out files. */
  3910.  
  3911. /* The a.out header. */
  3912.  
  3913. struct exec outheader;
  3914.  
  3915. #ifdef COFF_ENCAPSULATE
  3916. int need_coff_header;
  3917. struct coffheader coffheader;
  3918. #endif
  3919.  
  3920. /* Compute text_start and text_header_size for an a.out file.  */
  3921.  
  3922. void
  3923. initialize_a_out_text_start ()
  3924. {
  3925.   int magic;
  3926.  
  3927. #ifdef HUNK_INSTEAD_OF_A_OUT
  3928.   text_start = 0;
  3929.   return;
  3930. #endif
  3931.  
  3932.   switch (output_style)
  3933.     {
  3934.     case OUTPUT_RELOCATABLE:
  3935.     case OUTPUT_WRITABLE_TEXT:
  3936.       magic = OMAGIC;
  3937.       break;
  3938.     case OUTPUT_READONLY_TEXT:
  3939. #ifdef NMAGIC
  3940.       magic = NMAGIC;
  3941.       break;
  3942. #endif
  3943.     case OUTPUT_DEMAND_PAGED:
  3944.       magic = ZMAGIC;
  3945.       break;
  3946.     default:
  3947.       fatal ("unknown output style found (bug in ld)", (char *) 0);
  3948.       break;
  3949.     }
  3950.  
  3951.   /* Determine whether to count the header as part of
  3952.      the text size, and initialize the text size accordingly.
  3953.      This depends on the kind of system and on the output format selected.  */
  3954.   N_SET_MAGIC (outheader, magic);
  3955. #ifdef INITIALIZE_HEADER
  3956.   INITIALIZE_HEADER;
  3957. #endif
  3958.  
  3959.   text_header_size = sizeof (struct exec);
  3960. #ifdef COFF_ENCAPSULATE
  3961.   /* Don't write the coff header for the output of ld -A (since
  3962.      it is not executable by the kernel anyway).  */
  3963.   if (output_style != OUTPUT_RELOCATABLE && !file_table[0].just_syms_flag)
  3964.     {
  3965.       need_coff_header = 1;
  3966.       /* set this flag now, since it will change the values of N_TXTOFF, etc */
  3967.       N_SET_FLAGS (outheader, N_FLAGS_COFF_ENCAPSULATE);
  3968.       text_header_size += sizeof (struct coffheader);
  3969.     }
  3970. #endif
  3971.   if (text_header_size <= N_TXTOFF (outheader))
  3972.     text_header_size = 0;
  3973.   else
  3974.     text_header_size -= N_TXTOFF (outheader);
  3975.  
  3976. #ifdef _N_BASEADDR
  3977.   /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry. */
  3978.   outheader.a_entry = N_PAGSIZ(outheader);
  3979. #endif
  3980.  
  3981.   if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  3982.     text_start = N_TXTADDR (outheader);
  3983. }
  3984.  
  3985. /* Compute data_start once text_size is known. */
  3986.  
  3987. void
  3988. initialize_a_out_data_start ()
  3989. {
  3990. #ifdef HUNK_INSTEAD_OF_A_OUT
  3991.   data_start = 0;
  3992.   return;
  3993. #endif
  3994.  
  3995.   outheader.a_text = text_size;
  3996. #ifdef sequent
  3997.   outheader.a_text += N_ADDRADJ (outheader);
  3998.   if (entry_symbol == 0)
  3999.     entry_symbol = getsym ("start");
  4000. #endif
  4001.   if (! Tdata_flag_specified)
  4002.     data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
  4003. }
  4004.  
  4005. /* Compute offsets of various pieces of the a.out output file.  */
  4006.  
  4007. void
  4008. compute_a_out_section_offsets ()
  4009. {
  4010.   outheader.a_data = data_size;
  4011.   outheader.a_bss = bss_size;
  4012.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  4013.                : text_start + text_header_size);
  4014.  
  4015. #ifdef COFF_ENCAPSULATE
  4016.   if (need_coff_header)
  4017.     {
  4018.       /* We are encapsulating BSD format within COFF format.  */
  4019.       struct coffscn *tp, *dp, *bp;
  4020.  
  4021.       tp = &coffheader.scns[0];
  4022.       dp = &coffheader.scns[1];
  4023.       bp = &coffheader.scns[2];
  4024.  
  4025.       strcpy (tp->s_name, ".text");
  4026.       tp->s_paddr = text_start;
  4027.       tp->s_vaddr = text_start;
  4028.       tp->s_size = text_size;
  4029.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  4030.       tp->s_relptr = 0;
  4031.       tp->s_lnnoptr = 0;
  4032.       tp->s_nreloc = 0;
  4033.       tp->s_nlnno = 0;
  4034.       tp->s_flags = 0x20;
  4035.       strcpy (dp->s_name, ".data");
  4036.       dp->s_paddr = data_start;
  4037.       dp->s_vaddr = data_start;
  4038.       dp->s_size = data_size;
  4039.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  4040.       dp->s_relptr = 0;
  4041.       dp->s_lnnoptr = 0;
  4042.       dp->s_nreloc = 0;
  4043.       dp->s_nlnno = 0;
  4044.       dp->s_flags = 0x40;
  4045.       strcpy (bp->s_name, ".bss");
  4046.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  4047.       bp->s_vaddr = bp->s_paddr;
  4048.       bp->s_size = bss_size;
  4049.       bp->s_scnptr = 0;
  4050.       bp->s_relptr = 0;
  4051.       bp->s_lnnoptr = 0;
  4052.       bp->s_nreloc = 0;
  4053.       bp->s_nlnno = 0;
  4054.       bp->s_flags = 0x80;
  4055.  
  4056.       coffheader.f_magic = COFF_MAGIC;
  4057.       coffheader.f_nscns = 3;
  4058.       /* store an unlikely time so programs can
  4059.        * tell that there is a bsd header
  4060.        */
  4061.       coffheader.f_timdat = 1;
  4062.       coffheader.f_symptr = 0;
  4063.       coffheader.f_nsyms = 0;
  4064.       coffheader.f_opthdr = 28;
  4065.       coffheader.f_flags = 0x103;
  4066.       /* aouthdr */
  4067.       coffheader.magic = ZMAGIC;
  4068.       coffheader.vstamp = 0;
  4069.       coffheader.tsize = tp->s_size;
  4070.       coffheader.dsize = dp->s_size;
  4071.       coffheader.bsize = bp->s_size;
  4072.       coffheader.entry = outheader.a_entry;
  4073.       coffheader.text_start = tp->s_vaddr;
  4074.       coffheader.data_start = dp->s_vaddr;
  4075.     }
  4076. #endif
  4077.  
  4078.   if (strip_symbols == STRIP_ALL)
  4079.     nsyms = 0;
  4080.   else
  4081.     {
  4082.       nsyms = (defined_global_sym_count
  4083.            + undefined_global_sym_count);
  4084.       if (discard_locals == DISCARD_L)
  4085.     nsyms += non_L_local_sym_count;
  4086.       else if (discard_locals == DISCARD_NONE)
  4087.     nsyms += local_sym_count;
  4088.       /* One extra for following reference on indirects */
  4089.       if (output_style == OUTPUT_RELOCATABLE)
  4090. #ifndef NeXT
  4091.     nsyms += set_symbol_count + global_indirect_count;
  4092. #else
  4093.         nsyms += set_symbol_count;
  4094. #endif
  4095.     }
  4096.  
  4097.   if (strip_symbols == STRIP_NONE)
  4098.     nsyms += debugger_sym_count;
  4099.  
  4100.   outheader.a_syms = nsyms * sizeof (struct nlist);
  4101.  
  4102.   if (output_style == OUTPUT_RELOCATABLE)
  4103.     {
  4104.       outheader.a_trsize = text_reloc_size;
  4105.       outheader.a_drsize = data_reloc_size;
  4106.     }
  4107.   else
  4108.     {
  4109.       outheader.a_trsize = 0;
  4110.       outheader.a_drsize = 0;
  4111.     }
  4112.  
  4113.   /* Initialize the various file offsets.  */
  4114.  
  4115.   output_text_offset = N_TXTOFF (outheader);
  4116. #ifdef N_DATOFF
  4117.   output_data_offset = N_DATOFF (outheader);
  4118. #else
  4119.   output_data_offset = output_text_offset + text_size;
  4120. #endif
  4121. #ifdef N_TRELOFF
  4122.   output_trel_offset = N_TRELOFF (outheader);
  4123. #else
  4124.   output_trel_offset = output_data_offset + data_size;
  4125. #endif
  4126. #ifdef N_DRELOFF
  4127.   output_drel_offset = N_DRELOFF (outheader);
  4128. #else
  4129.   output_drel_offset = output_trel_offset + text_reloc_size;
  4130. #endif
  4131.   output_syms_offset = N_SYMOFF (outheader);
  4132.   output_strs_offset = N_STROFF (outheader);
  4133. }
  4134.  
  4135. /* Compute more section offsets once the size of the string table is known.  */
  4136.  
  4137. void
  4138. compute_more_a_out_section_offsets ()
  4139. {
  4140.   output_symseg_offset = output_strs_offset + output_strs_size;
  4141. }
  4142.  
  4143. /* Write the a.out header once everything else is known.  */
  4144.  
  4145. void
  4146. write_a_out_header ()
  4147. {
  4148.   lseek (outdesc, 0L, 0);
  4149.  
  4150. #ifdef COFF_ENCAPSULATE
  4151.   if (need_coff_header)
  4152.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  4153. #endif
  4154.  
  4155.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  4156.  
  4157.   /* Output whatever padding is required in the executable file
  4158.      between the header and the start of the text.  */
  4159.  
  4160. #ifndef COFF_ENCAPSULATE
  4161.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  4162. #endif
  4163. }
  4164.  
  4165. #endif
  4166.  
  4167. #ifdef MACH_O
  4168.  
  4169. /* Stuff pertaining to creating Mach-O files. */
  4170.  
  4171. /* Convert the Mach-O style n_sect references into something the rest
  4172.    of the loader can understand.  */
  4173.  
  4174. void
  4175. translate_mach_o_symbols (entry)
  4176.      struct file_entry *entry;
  4177. {
  4178.   int i, n, g;
  4179.   struct nlist *sym;
  4180.  
  4181.   n = entry->syms_size / sizeof (struct nlist);
  4182.   for (i = 0; i < n; ++i)
  4183.     if (((sym = &entry->symbols[i])->n_type & ~N_EXT) == N_SECT)
  4184.       {
  4185.     if (sym->n_sect == entry->text_ordinal)
  4186.       sym->n_type = (sym->n_type & N_EXT) | N_TEXT;
  4187.     else if (sym->n_sect == entry->data_ordinal)
  4188.       sym->n_type = (sym->n_type & N_EXT) | N_DATA;
  4189.     else if (sym->n_sect == entry->bss_ordinal)
  4190.       sym->n_type = (sym->n_type & N_EXT) | N_BSS;
  4191.     else
  4192.       fatal_with_file ("unknown section referenced in symbols of ", entry);
  4193.     sym->n_sect = 0;
  4194.       }
  4195.     else if ((sym = &entry->symbols[i])->n_type == N_SLINE)
  4196.       {
  4197.     if (sym->n_sect == entry->text_ordinal)
  4198.       sym->n_type = N_SLINE;
  4199.     else if (sym->n_sect == entry->data_ordinal)
  4200.       sym->n_type = N_DSLINE;
  4201.     else if (sym->n_sect == entry->bss_ordinal)
  4202.       sym->n_type = N_BSLINE;
  4203.     else
  4204.       fatal_with_file ("unknown section referenced in debugging symbols of ", entry);
  4205.       }
  4206. }
  4207.  
  4208. /* Convert Mach-O style relocation info into a.out style relocation
  4209.    info internally.  */
  4210. void
  4211. translate_mach_o_relocation (entry, reloc, count)
  4212.      struct file_entry *entry;
  4213.      struct relocation_info *reloc;
  4214.      int count;
  4215. {
  4216.   int i;
  4217.  
  4218.   for (i = 0; i < count; ++i)
  4219.     if (!RELOC_EXTERN_P(&reloc[i]))
  4220.       if (RELOC_TYPE(&reloc[i]) == R_ABS)
  4221.     RELOC_TYPE(&reloc[i]) = N_ABS;
  4222.       else if (RELOC_TYPE(&reloc[i]) == entry->text_ordinal)
  4223.     RELOC_TYPE(&reloc[i]) = N_TEXT;
  4224.       else if (RELOC_TYPE(&reloc[i]) == entry->data_ordinal)
  4225.     RELOC_TYPE(&reloc[i]) = N_DATA;
  4226.       else if (RELOC_TYPE(&reloc[i]) == entry->bss_ordinal)
  4227.     RELOC_TYPE(&reloc[i]) = N_BSS;
  4228.       else
  4229.     fatal_with_file ("unknown section ordinal in relocation info of ", entry);
  4230. }
  4231.  
  4232. /* Header structure for OUTPUT_RELOCATABLE.  */
  4233.  
  4234. struct
  4235. {
  4236.   struct mach_header header;
  4237.   struct segment_command segment;
  4238.   struct section text;
  4239.   struct section data;
  4240.   struct section bss;
  4241.   struct symtab_command symtab;
  4242. #ifdef LC_SYMSEG
  4243.   struct symseg_command symseg;
  4244. #endif
  4245. } m_object;
  4246.  
  4247. #ifdef NeXT
  4248. #define CPU_TYPE CPU_TYPE_MC68030
  4249. #define CPU_SUBTYPE CPU_SUBTYPE_NeXT
  4250. #define THREAD_FLAVOR NeXT_THREAD_STATE_REGS
  4251. #define THREAD_COUNT NeXT_THREAD_STATE_REGS_COUNT
  4252. typedef struct NeXT_thread_state_regs thread_state;
  4253. #define thread_state_entry_field pc
  4254. #endif
  4255.  
  4256. /* Header structure for all executable output forms.  */
  4257.  
  4258. struct
  4259. {
  4260.   struct mach_header header;
  4261.   struct segment_command pagezero;
  4262.   struct segment_command text_segment;
  4263.   struct section text;
  4264.   struct segment_command data_segment;
  4265.   struct section data;
  4266.   struct section bss;
  4267.   struct thread_command unixthread;
  4268.   unsigned long int flavor;
  4269.   unsigned long int count;
  4270.   thread_state state;
  4271.   struct symtab_command symtab;
  4272. #ifdef LC_SYMSEG
  4273.   struct symseg_command symseg;
  4274. #endif
  4275. } m_exec;
  4276.  
  4277. /* Compute text_start and text_header_size for an a.out file.  */
  4278.  
  4279. void
  4280. initialize_mach_o_text_start ()
  4281. {
  4282.   if (output_style != OUTPUT_RELOCATABLE)
  4283.     {
  4284.       text_header_size = sizeof m_exec;
  4285.       if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  4286.     /* We reserve the first page of an executable to trap NULL dereferences.  */
  4287.     text_start = page_size;
  4288.     }
  4289. }
  4290.  
  4291. /* Compute data_start once text_size is known.  */
  4292.  
  4293. void
  4294. initialize_mach_o_data_start ()
  4295. {
  4296.   if (! Tdata_flag_specified)
  4297.     data_start = text_start + text_size;
  4298. }
  4299.  
  4300. /* Compute offsets of various pieces of the Mach-O output file.  */
  4301. void
  4302. compute_mach_o_section_offsets ()
  4303. {
  4304.   int header_size, trsize, drsize;
  4305.  
  4306.   switch (output_style)
  4307.     {
  4308.     case OUTPUT_RELOCATABLE:
  4309.       header_size = sizeof m_object;
  4310.       break;
  4311.     default:
  4312.       header_size = sizeof m_exec;
  4313.       break;
  4314.     }
  4315.  
  4316.   if (strip_symbols == STRIP_ALL)
  4317.     nsyms = 0;
  4318.   else
  4319.     {
  4320.       nsyms = (defined_global_sym_count
  4321.            + undefined_global_sym_count);
  4322.       if (discard_locals == DISCARD_L)
  4323.     nsyms += non_L_local_sym_count;
  4324.       else if (discard_locals == DISCARD_NONE)
  4325.     nsyms += local_sym_count;
  4326.       /* One extra for following reference on indirects */
  4327.       if (output_style == OUTPUT_RELOCATABLE)
  4328. #ifndef NeXT
  4329.     nsyms += set_symbol_count + global_indirect_count;
  4330. #else
  4331.         nsyms += set_symbol_count;
  4332. #endif
  4333.     }
  4334.  
  4335.   if (strip_symbols == STRIP_NONE)
  4336.     nsyms += debugger_sym_count;
  4337.  
  4338.   output_text_offset = header_size;
  4339.   output_data_offset = output_text_offset + text_size;
  4340.   output_trel_offset = output_data_offset + data_size;
  4341.   if (output_style == OUTPUT_RELOCATABLE)
  4342.     trsize = text_reloc_size, drsize = data_reloc_size;
  4343.   else
  4344.     trsize = drsize = 0;
  4345.   output_drel_offset = output_trel_offset + trsize;
  4346.   output_syms_offset = output_drel_offset + drsize;
  4347.   output_strs_offset = output_syms_offset + nsyms * sizeof (struct nlist);
  4348. }
  4349.  
  4350. /* Compute more section offsets once the size of the string table is known.  */
  4351. void
  4352. compute_more_mach_o_section_offsets ()
  4353. {
  4354.   output_symseg_offset = output_strs_offset + output_strs_size;
  4355. }
  4356.  
  4357. /* Write the Mach-O header once everything else is known.  */
  4358.  
  4359. void
  4360. write_mach_o_header ()
  4361. {
  4362.   struct mach_header header;
  4363.   struct section text, data, bss;
  4364.   struct symtab_command symtab;
  4365. #ifdef LC_SYMSEG
  4366.   struct symseg_command symseg;
  4367. #endif
  4368.   thread_state state;
  4369.  
  4370.   lseek (outdesc, 0L, 0);
  4371.  
  4372.  
  4373.   header.magic = MH_MAGIC;
  4374.   header.cputype = CPU_TYPE;
  4375.   header.cpusubtype = CPU_SUBTYPE;
  4376.   header.filetype = output_style == OUTPUT_RELOCATABLE ? MH_OBJECT : MH_EXECUTE;
  4377. #ifdef LC_SYMSEG
  4378.   switch (output_style)
  4379.     {
  4380.     case OUTPUT_RELOCATABLE:
  4381.       header.ncmds = 3;
  4382.       header.sizeofcmds = sizeof m_object - sizeof header;
  4383.       break;
  4384.     default:
  4385.       header.ncmds = 6;
  4386.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4387.       break;
  4388.     }
  4389. #else
  4390.   switch (output_style)
  4391.     {
  4392.     case OUTPUT_RELOCATABLE:
  4393.       header.ncmds = 2;
  4394.       header.sizeofcmds = sizeof m_object - sizeof header;
  4395.       break;
  4396.     default:
  4397.       header.ncmds = 5;
  4398.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4399.       break;
  4400.     }
  4401. #endif
  4402.   header.flags = undefined_global_sym_count ? 0 : MH_NOUNDEFS;
  4403.  
  4404.   bzero((char *) &text, sizeof text);
  4405.   strncpy(text.sectname, SECT_TEXT, sizeof text.sectname);
  4406.   strncpy(text.segname, SEG_TEXT, sizeof text.segname);
  4407.   text.addr = text_start;
  4408.   text.size = text_size;
  4409.   text.offset = output_text_offset;
  4410.   text.align = text.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4411.   text.reloff = output_trel_offset;
  4412.   text.nreloc = output_style == OUTPUT_RELOCATABLE
  4413.     ? text_reloc_size / sizeof (struct relocation_info) : 0;
  4414.   text.flags = 0;
  4415.  
  4416.   bzero((char *) &data, sizeof data);
  4417.   strncpy(data.sectname, SECT_DATA, sizeof data.sectname);
  4418.   strncpy(data.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4419.       sizeof data.segname);
  4420.   data.addr = data_start;
  4421.   data.size = data_size;
  4422.   data.offset = output_data_offset;
  4423.   data.align = data.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4424.   data.reloff = output_drel_offset;
  4425.   data.nreloc = output_style == OUTPUT_RELOCATABLE
  4426.     ? data_reloc_size / sizeof (struct relocation_info) : 0;
  4427.   data.flags = 0;
  4428.  
  4429.   bzero((char *) &bss, sizeof bss);
  4430.   strncpy(bss.sectname, SECT_BSS, sizeof data.sectname);
  4431.   strncpy(bss.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4432.       sizeof bss.segname);
  4433.   bss.addr = data_start + data_size;
  4434.   bss.size = bss_size;
  4435.   bss.align = bss.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4436.   bss.reloff = 0;
  4437.   bss.nreloc = 0;
  4438.   bss.flags = S_ZEROFILL;
  4439.  
  4440.   symtab.cmd = LC_SYMTAB;
  4441.   symtab.cmdsize = sizeof symtab;
  4442.   symtab.symoff = output_syms_offset;
  4443.   symtab.nsyms = output_syms_size / sizeof (struct nlist);
  4444.   symtab.stroff = output_strs_offset;
  4445.   symtab.strsize = output_strs_size;
  4446.  
  4447. #ifdef LC_SYMSEG
  4448.   symseg.cmd = LC_SYMSEG;
  4449.   symseg.cmdsize = sizeof symseg;
  4450.   symseg.offset = output_symseg_offset;
  4451.   symseg.size = output_symseg_size;
  4452. #endif
  4453.  
  4454.   switch (output_style)
  4455.     {
  4456.     case OUTPUT_RELOCATABLE:
  4457.       m_object.header = header;
  4458.       m_object.segment.cmd = LC_SEGMENT;
  4459.       m_object.segment.cmdsize = sizeof (struct segment_command) + 3 * sizeof (struct section);
  4460.       strncpy(m_object.segment.segname, SEG_TEXT, sizeof m_object.segment.segname);
  4461.       m_object.segment.vmaddr = 0;
  4462.       m_object.segment.vmsize = text.size + data.size + bss.size;
  4463.       m_object.segment.fileoff = text.offset;
  4464.       m_object.segment.filesize = text.size + data.size;
  4465.       m_object.segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4466.       m_object.segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4467.       m_object.segment.nsects = 3;
  4468.       m_object.segment.flags = 0;
  4469.       m_object.text = text;
  4470.       m_object.data = data;
  4471.       m_object.bss = bss;
  4472.       m_object.symtab = symtab;
  4473. #ifdef LC_SYMSEG
  4474.       m_object.symseg = symseg;
  4475. #endif
  4476.       mywrite((char *) &m_object, 1, sizeof m_object, outdesc);
  4477.       break;
  4478.  
  4479.     default:
  4480.       m_exec.header = header;
  4481.       m_exec.pagezero.cmd = LC_SEGMENT;
  4482.       m_exec.pagezero.cmdsize = sizeof (struct segment_command);
  4483.       strncpy(m_exec.pagezero.segname, SEG_PAGEZERO, sizeof m_exec.pagezero.segname);
  4484.       m_exec.pagezero.vmaddr = 0;
  4485.       m_exec.pagezero.vmsize = page_size;
  4486.       m_exec.pagezero.fileoff = 0;
  4487.       m_exec.pagezero.filesize = 0;
  4488.       m_exec.pagezero.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4489.       m_exec.pagezero.initprot = 0;
  4490.       m_exec.pagezero.nsects = 0;
  4491.       m_exec.pagezero.flags = 0;
  4492.       m_exec.text_segment.cmd = LC_SEGMENT;
  4493.       m_exec.text_segment.cmdsize = sizeof (struct segment_command) + sizeof (struct section);
  4494.       strncpy(m_exec.text_segment.segname, SEG_TEXT, sizeof m_exec.text_segment.segname);
  4495.       m_exec.text_segment.vmaddr = text_start;
  4496.       m_exec.text_segment.vmsize = text_size;
  4497.       m_exec.text_segment.fileoff = output_text_offset;
  4498.       m_exec.text_segment.filesize = text_size;
  4499.       m_exec.text_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4500.       m_exec.text_segment.initprot = VM_PROT_READ | VM_PROT_EXECUTE;
  4501.       if (output_style == OUTPUT_WRITABLE_TEXT)
  4502.     m_exec.text_segment.initprot |= VM_PROT_WRITE;
  4503.       m_exec.text_segment.nsects = 1;
  4504.       m_exec.text_segment.flags = 0;
  4505.       m_exec.text = text;
  4506.       m_exec.data_segment.cmd = LC_SEGMENT;
  4507.       m_exec.data_segment.cmdsize = sizeof (struct segment_command) + 2 * sizeof (struct section);
  4508.       strncpy(m_exec.data_segment.segname, SEG_DATA, sizeof m_exec.data_segment.segname);
  4509.       m_exec.data_segment.vmaddr = data_start;
  4510.       m_exec.data_segment.vmsize = data_size + bss_size;
  4511.       m_exec.data_segment.fileoff = output_data_offset;
  4512.       m_exec.data_segment.filesize = data_size;
  4513.       m_exec.data_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4514.       m_exec.data_segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4515.       m_exec.data_segment.nsects = 2;
  4516.       m_exec.data_segment.flags = 0;
  4517.       m_exec.data = data;
  4518.       m_exec.bss = bss;
  4519.       m_exec.unixthread.cmd = LC_UNIXTHREAD;
  4520.       m_exec.unixthread.cmdsize
  4521.     = sizeof (struct thread_command) + 2 * sizeof (long int) + sizeof (thread_state);
  4522.       m_exec.flavor = THREAD_FLAVOR;
  4523.       m_exec.count = THREAD_COUNT;
  4524.       m_exec.state.thread_state_entry_field = entry_symbol
  4525.     ? entry_symbol->value : text_start + text_header_size;
  4526.       m_exec.symtab = symtab;
  4527. #ifdef LC_SYMSEG
  4528.       m_exec.symseg = symseg;
  4529. #endif
  4530.       mywrite((char *) &m_exec, 1, sizeof m_exec, outdesc);
  4531.       break;
  4532.     }
  4533. }
  4534.  
  4535. /* Translate a.out style symbols into Mach-O style symbols.  */
  4536.  
  4537. void
  4538. generate_mach_o_symbols (syms, nsyms)
  4539.      struct nlist *syms;
  4540.      int nsyms;
  4541. {
  4542.   int i;
  4543.  
  4544.   for (i = 0; i < nsyms; ++i)
  4545.     switch (syms[i].n_type)
  4546.       {
  4547.       case N_TEXT:
  4548.       case N_TEXT | N_EXT:
  4549.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4550.     syms[i].n_sect = 1;    /* text section ordinal */
  4551.     break;
  4552.       case N_DATA:
  4553.       case N_DATA | N_EXT:
  4554.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4555.     syms[i].n_sect = 2;    /* data section ordinal */
  4556.     break;
  4557.       case N_BSS:
  4558.       case N_BSS | N_EXT:
  4559.     syms[i].n_type = syms[i].n_type & N_EXT | N_BSS;
  4560.     syms[i].n_sect = 3;    /* bss section ordinal */
  4561.     break;
  4562.       case N_SLINE:
  4563.     syms[i].n_type = N_SLINE;
  4564.     syms[i].n_sect = 1;    /* text section ordinal */
  4565.     break;
  4566.       case N_DSLINE:
  4567.     syms[i].n_type = N_SLINE;
  4568.     syms[i].n_sect = 2;    /* data section ordinal */
  4569.     break;
  4570.       case N_BSLINE:
  4571.     syms[i].n_type = N_SLINE;
  4572.     syms[i].n_sect = 3;    /* bss section ordinal */
  4573.     break;
  4574.       }
  4575. }
  4576.  
  4577. /* Translate a.out style relocation info into Mach-O style relocation
  4578.    info.  */
  4579.  
  4580. void
  4581. generate_mach_o_relocations (reloc, nreloc)
  4582.      struct relocation_info *reloc;
  4583.      int nreloc;
  4584. {
  4585.   int i;
  4586.  
  4587.   for (i = 0; i < nreloc; ++i)
  4588.     if (!RELOC_EXTERN_P (&reloc[i]))
  4589.       switch (RELOC_TYPE (&reloc[i]))
  4590.     {
  4591.     case N_ABS:
  4592.     case N_ABS | N_EXT:
  4593.       RELOC_TYPE (&reloc[i]) = R_ABS;
  4594.       break;
  4595.     case N_TEXT:
  4596.     case N_TEXT | N_EXT:
  4597.       RELOC_TYPE (&reloc[i]) = 1; /* output text section ordinal */
  4598.       break;
  4599.     case N_DATA:
  4600.     case N_DATA | N_EXT:
  4601.       RELOC_TYPE (&reloc[i]) = 2; /* output data section ordinal */
  4602.       break;
  4603.     case N_BSS:
  4604.     case N_BSS | N_EXT:
  4605.       RELOC_TYPE (&reloc[i]) = 3; /* output bss section ordinal */
  4606.       break;
  4607.     }
  4608. }
  4609.  
  4610. #endif
  4611.  
  4612. /* The following functions are simple switches according to the
  4613.    output style.  */
  4614.  
  4615. /* Compute text_start and text_header_size as appropriate for the
  4616.    output format.  */
  4617.  
  4618. void
  4619. initialize_text_start ()
  4620. {
  4621. #ifdef A_OUT
  4622.   if (output_file_type == IS_A_OUT)
  4623.     {
  4624.       initialize_a_out_text_start ();
  4625.       return;
  4626.     }
  4627. #endif
  4628. #ifdef MACH_O
  4629.   if (output_file_type == IS_MACH_O)
  4630.     {
  4631.       initialize_mach_o_text_start ();
  4632.       return;
  4633.     }
  4634. #endif
  4635.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4636. }
  4637.  
  4638. /* Initialize data_start as appropriate to the output format, once text_size
  4639.    is known.  */
  4640.  
  4641. void
  4642. initialize_data_start ()
  4643. {
  4644. #ifdef A_OUT
  4645.   if (output_file_type == IS_A_OUT)
  4646.     {
  4647.       initialize_a_out_data_start ();
  4648.       return;
  4649.     }
  4650. #endif
  4651. #ifdef MACH_O
  4652.   if (output_file_type == IS_MACH_O)
  4653.     {
  4654.       initialize_mach_o_data_start ();
  4655.       return;
  4656.     }
  4657. #endif
  4658.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4659. }
  4660.  
  4661. /* Compute offsets of the various sections within the output file.  */
  4662.  
  4663. void
  4664. compute_section_offsets ()
  4665. {
  4666. #ifdef A_OUT
  4667.   if (output_file_type == IS_A_OUT)
  4668.     {
  4669.       compute_a_out_section_offsets ();
  4670.       return;
  4671.     }
  4672. #endif
  4673. #ifdef MACH_O
  4674.   if (output_file_type == IS_MACH_O)
  4675.     {
  4676.       compute_mach_o_section_offsets ();
  4677.       return;
  4678.     }
  4679. #endif
  4680.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4681. }
  4682.  
  4683. /* Compute more section offsets, once the size of the string table
  4684.    is finalized.  */
  4685. void
  4686. compute_more_section_offsets ()
  4687. {
  4688. #ifdef A_OUT
  4689.   if (output_file_type == IS_A_OUT)
  4690.     {
  4691.       compute_more_a_out_section_offsets ();
  4692.       return;
  4693.     }
  4694. #endif
  4695. #ifdef MACH_O
  4696.   if (output_file_type == IS_MACH_O)
  4697.     {
  4698.       compute_more_mach_o_section_offsets ();
  4699.       return;
  4700.     }
  4701. #endif
  4702.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4703. }
  4704.  
  4705. /* Write the output file header, once everything is known.  */
  4706. void
  4707. write_header ()
  4708. {
  4709. #ifdef HUNK_INSTEAD_OF_A_OUT
  4710.   conditionally_rewrite_headers ();
  4711.   return;
  4712. #else
  4713. #ifdef A_OUT
  4714.   if (output_file_type == IS_A_OUT)
  4715.     {
  4716.       write_a_out_header ();
  4717.       return;
  4718.     }
  4719. #endif
  4720. #ifdef MACH_O
  4721.   if (output_file_type == IS_MACH_O)
  4722.     {
  4723.       write_mach_o_header ();
  4724.       return;
  4725.     }
  4726. #endif
  4727. #endif
  4728.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4729. }
  4730.  
  4731. /* Write the output file */
  4732.  
  4733. void
  4734. write_output ()
  4735. {
  4736.   struct stat statbuf;
  4737.   int filemode, mask;
  4738.  
  4739.   /* Remove the old file in case it is owned by someone else.
  4740.      This prevents spurious "not owner" error messages.
  4741.      Don't check for errors from unlink; we don't really care
  4742.      whether it worked.
  4743.  
  4744.      Note that this means that if the output file is hard linked,
  4745.      the other names will still have the old contents.  This is
  4746.      the way Unix ld works; I'm going to consider it a feature.  */
  4747.   (void) unlink (output_filename);
  4748.   
  4749.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4750.   if (outdesc < 0) perror_name (output_filename);
  4751.  
  4752. #ifndef MCH_AMIGA
  4753.   if (fstat (outdesc, &statbuf) < 0)
  4754.     perror_name (output_filename);
  4755.  
  4756.   filemode = statbuf.st_mode;
  4757.  
  4758.   /* this wouldn't work anyway, "file in use, error"... */
  4759.   chmod (output_filename, filemode & ~0111);
  4760. #endif
  4761.  
  4762.   /* on the Amiga, the following call DOES set the symbol offset, but
  4763.    * it does it wrong, we'll be able to do it right, as soon as all the
  4764.    * other data has been written.. */
  4765.  
  4766.   /* Calculate the offsets of the various pieces of the output file.  */
  4767.   compute_section_offsets ();
  4768.  
  4769. #ifdef HUNK_INSTEAD_OF_A_OUT
  4770.   /* get ready to collect information where all symbols
  4771.    * go. Since this has to be done only once, we'll later be able to 
  4772.    * output the right symbol-hunk after the right (code/data/bss-)hunk. */
  4773.   init_symbol_hunks ();
  4774.   look_for_symbols ();
  4775. #endif
  4776.  
  4777.   /* Output the text and data segments, relocating as we go.  */
  4778.   write_text ();
  4779.   write_data ();
  4780. #ifdef HUNK_INSTEAD_OF_A_OUT
  4781.   if (datadata_relocs_offset)
  4782.     write_datadata_relocs ();
  4783.  
  4784.   write_bss ();
  4785.   if (number_of_debug_hunk != -1)
  4786.     {
  4787.       /* ok, lets output the start of the debug hunk */
  4788.       offset_of_debug_hunk = lseek(outdesc, 0L, 2);
  4789.  
  4790.       dh.id = 0x3f1;     /* HUNK_DEBUG */
  4791.       dh.len = 0;        /* we'll fill this in later */
  4792.       dh.magic = ZMAGIC; /* when wishes came true... */
  4793.       dh.syms = outheader.a_syms;
  4794.       mywrite(&dh, sizeof dh, 1, outdesc);
  4795.  
  4796.       output_syms_offset   = lseek(outdesc, 0L, 2);
  4797.       output_strs_offset   = output_syms_offset + dh.syms;
  4798.  
  4799.       /* since we later will seek forward and backward to fill in each files
  4800.        * symbol- and string-table, we have to create the needed space, that
  4801.        * will be seeked over, since on an empty file, lseek(fd, 10, 0) will 
  4802.        * position to byte 10 on Unix, but will just generate an error under
  4803.        * AmigaDOS and stay at position 0. */
  4804.  
  4805.       /* this will just write garbage, but thats enough:-)) */
  4806.       mywrite(&output_strs_offset, dh.syms+4, 1, outdesc);
  4807.       lseek(outdesc, output_syms_offset, 0);
  4808.     }
  4809. #endif
  4810.  
  4811.   /* Output the merged relocation info, if requested with `-r'.  */
  4812.   if (output_style == OUTPUT_RELOCATABLE)
  4813.     write_rel ();
  4814.  
  4815.   /* Output the symbol table (both globals and locals).  */
  4816.   write_syms ();
  4817.  
  4818.   /* At this point the total size of the symbol table and string table
  4819.      are finalized.  */
  4820.   compute_more_section_offsets ();
  4821.  
  4822. #ifndef HUNK_INSTEAD_OF_A_OUT
  4823.   /* I don't support GDB-symbol segments, they aren't used anymore by
  4824.    * the newer versions of gdb, BUT of course, if somebody needs them..
  4825.    * that's exactly why I introduced the "dh.strs" Parameter, so that
  4826.    * you could - as in Unix - append these segments at the end of the file */
  4827.  
  4828.   /* Copy any GDB symbol segments from input files.  */
  4829.   write_symsegs ();
  4830. #endif
  4831.  
  4832.   /* Now that everything is known about the output file, write its header.  */
  4833.   write_header ();
  4834.  
  4835.   close (outdesc);
  4836.  
  4837. #ifndef HUNK_INSTEAD_OF_A_OUT
  4838.   mask = umask (0);
  4839.   umask (mask);
  4840.  
  4841.   if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
  4842.     perror_name (output_filename);
  4843. #endif
  4844. }
  4845.  
  4846. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  4847. #ifdef HUNK_INSTEAD_OF_A_OUT
  4848. void write_hunk_header();
  4849. #endif
  4850.  
  4851. /* Relocate the text segment of each input file
  4852.    and write to the output file.  */
  4853.  
  4854. void
  4855. write_text ()
  4856. {
  4857.   if (trace_files)
  4858.     fprintf (stderr, "Copying and relocating text:\n\n");
  4859.  
  4860. #ifdef HUNK_INSTEAD_OF_A_OUT
  4861.   /* this is a definitive write, we don't need to rewrite this out, since
  4862.    * the yet undefined sizes of the reloc-hunks don't go into the 
  4863.    * header-hunk */
  4864.   write_hunk_header(outdesc);
  4865.   init_reloc_hunk();
  4866.  
  4867.   /* and if there's no code-hunk, we can return here.. no sense in
  4868.    * complicately doing just nothing... */
  4869.   if (number_of_code_hunk == -1) return;
  4870.  
  4871.   /* else start the code-hunk */
  4872.   {
  4873.      long code_header[2];
  4874.      code_header[0] = 0x3e9;
  4875.      code_header[1] = LONGSIZE(text_size);
  4876.      mywrite(code_header, 1, sizeof code_header, outdesc);
  4877.   }
  4878. #else
  4879.   lseek (outdesc, output_text_offset + text_header_size, 0);
  4880. #endif
  4881.  
  4882.   each_full_file (copy_text, 0);
  4883. #ifdef HUNK_INSTEAD_OF_A_OUT
  4884.   if (output_datadata_relocs && numdatadata_relocs)
  4885.     {
  4886.       int i, zero = 0;
  4887.       /* include the size-field, -> <= . The `real' values come later */
  4888.       datadata_relocs_offset = lseek (outdesc, 0, SEEK_CUR);
  4889.       for (i = 0; i <= numdatadata_relocs; i ++)
  4890.         mywrite (&zero, 1, sizeof (long), outdesc);
  4891.     }
  4892. #endif
  4893.  
  4894.   file_close ();
  4895.  
  4896.   if (trace_files)
  4897.     fprintf (stderr, "\n");
  4898.  
  4899.   padfile (text_pad, outdesc);
  4900.  
  4901. #ifdef HUNK_INSTEAD_OF_A_OUT
  4902.   write_reloc_hunk();
  4903.   write_symbol_hunk(number_of_code_hunk);
  4904.   {
  4905.     long hunk_end = 0x3f2;
  4906.     mywrite(&hunk_end, 1, sizeof(long), outdesc);
  4907.   }
  4908. #endif
  4909. }
  4910.  
  4911. /* Read in all of the relocation information */
  4912.  
  4913. void
  4914. read_relocation ()
  4915. {
  4916.   each_full_file (read_file_relocation, 0);
  4917. }
  4918.  
  4919. /* Read in the relocation sections of ENTRY if necessary */
  4920.  
  4921. void
  4922. read_file_relocation (entry)
  4923.      struct file_entry *entry;
  4924. {
  4925.   register struct relocation_info *reloc;
  4926.   int desc;
  4927.   int read_return;
  4928.  
  4929.   desc = -1;
  4930.   if (!entry->textrel)
  4931.     {
  4932.       reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
  4933.       desc = file_open (entry);
  4934.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4935.       if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
  4936.     {
  4937.       fprintf (stderr, "Return from read: %d\n", read_return);
  4938.       fatal_with_file ("premature eof in text relocation of ", entry);
  4939.     }
  4940.       entry->textrel = reloc;
  4941.     }
  4942.  
  4943.   if (!entry->datarel)
  4944.     {
  4945.       reloc = (struct relocation_info *) xmalloc (entry->data_reloc_size);
  4946.       if (desc == -1) desc = file_open (entry);
  4947.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  4948.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  4949.     fatal_with_file ("premature eof in data relocation of ", entry);
  4950.       entry->datarel = reloc;
  4951.     }
  4952.  
  4953. #ifdef MACH_O
  4954.   if (entry->file_type == IS_MACH_O)
  4955.     {
  4956.       translate_mach_o_relocation (entry, entry->textrel,
  4957.                    entry->text_reloc_size / sizeof (struct relocation_info));
  4958.       translate_mach_o_relocation (entry, entry->datarel,
  4959.                    entry->data_reloc_size / sizeof (struct relocation_info));
  4960.     }
  4961. #endif
  4962. }
  4963.  
  4964. /* Read the text segment contents of ENTRY, relocate them,
  4965.    and write the result to the output file.
  4966.    If `-r', save the text relocation for later reuse.  */
  4967.  
  4968. void
  4969. copy_text (entry)
  4970.      struct file_entry *entry;
  4971. {
  4972.   register char *bytes;
  4973.   register int desc;
  4974.   register struct relocation_info *reloc;
  4975.  
  4976.   if (trace_files)
  4977.     prline_file_name (entry, stderr);
  4978.  
  4979.   desc = file_open (entry);
  4980.  
  4981.   /* Allocate space for the file's text section */
  4982.  
  4983.   bytes = (char *) alloca (entry->text_size);
  4984.  
  4985.   /* Deal with relocation information however is appropriate */
  4986.  
  4987.   if (entry->textrel)  reloc = entry->textrel;
  4988.   else if (output_style == OUTPUT_RELOCATABLE)
  4989.     {
  4990.       read_file_relocation (entry);
  4991.       reloc = entry->textrel;
  4992.     }
  4993.   else
  4994.     {
  4995.       reloc = (struct relocation_info *) alloca (entry->text_reloc_size);
  4996.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4997.       if (entry->text_reloc_size != read (desc, reloc, entry->text_reloc_size))
  4998.     fatal_with_file ("premature eof in text relocation of ", entry);
  4999. #ifdef MACH_O
  5000.       if (entry->file_type == IS_MACH_O)
  5001.     translate_mach_o_relocation (entry, reloc,
  5002.                      entry->text_reloc_size / sizeof (struct relocation_info));
  5003. #endif
  5004.     }
  5005.  
  5006.   /* Read the text section into core.  */
  5007.  
  5008.   lseek (desc, entry->starting_offset + entry->text_offset, L_SET);
  5009.   if (entry->text_size != read (desc, bytes, entry->text_size))
  5010.     fatal_with_file ("premature eof in text section of ", entry);
  5011.  
  5012.   /* Relocate the text according to the text relocation.  */
  5013.   perform_relocation (bytes, entry->text_start_address - entry->orig_text_address,
  5014.               entry->text_size, reloc, entry->text_reloc_size, entry);
  5015.  
  5016.   /* Write the relocated text to the output file.  */
  5017.  
  5018.   mywrite (bytes, 1, entry->text_size, outdesc);
  5019. }
  5020.  
  5021. /* Relocate the data segment of each input file
  5022.    and write to the output file.  */
  5023.  
  5024. void
  5025. write_data ()
  5026. {
  5027.   if (trace_files)
  5028.     fprintf (stderr, "Copying and relocating data:\n\n");
  5029.  
  5030. #ifndef HUNK_INSTEAD_OF_A_OUT
  5031.   lseek (outdesc, output_data_offset, 0);
  5032. #else
  5033.   /* just have to hope that the file is positioned correctly.. */
  5034.   init_reloc_hunk();
  5035.   /* start a data-hunk, if there is data to be output */
  5036.   if (number_of_data_hunk == -1) return;
  5037.  
  5038.   {
  5039.     long data_header[2];
  5040.     data_header[0] = 0x3ea;
  5041.     if (databss_together)
  5042.       data_header[1] = LONGSIZE(data_size + bss_size);
  5043.     else
  5044.       data_header[1] = LONGSIZE(data_size);
  5045.     mywrite(data_header, 1, sizeof data_header, outdesc);
  5046.   }
  5047. #endif
  5048.  
  5049.   each_full_file (copy_data, 0);
  5050.   file_close ();
  5051.  
  5052.   /* Write out the set element vectors.  See digest symbols for
  5053.      description of length of the set vector section.  */
  5054.  
  5055.   if (set_vector_count)
  5056.     {
  5057. #ifdef HUNK_INSTEAD_OF_A_OUT
  5058.      /* this and mywrite later: inverted set_symbol_count and 
  5059.       * set_vector_count, guess they were mixed up before   ### mw */
  5060.  
  5061.       relocate_set_vectors (set_vectors,
  5062.                 2 * set_vector_count + set_symbol_count);
  5063. #endif
  5064. #if 0
  5065.       mywrite (set_vectors, 2 * set_symbol_count + set_vector_count,
  5066.            sizeof (unsigned long), outdesc);
  5067. #else
  5068.       mywrite (set_vectors, 2 * set_vector_count + set_symbol_count,
  5069.            sizeof (unsigned long), outdesc);
  5070. #endif
  5071.     }
  5072.  
  5073.   if (trace_files)
  5074.     fprintf (stderr, "\n");
  5075.  
  5076.   padfile (data_pad, outdesc);
  5077.  
  5078. #ifdef HUNK_INSTEAD_OF_A_OUT
  5079.   if (databss_together && bss_size)
  5080.     {
  5081.       /* dump zeros */
  5082.       int i, zero = 0;
  5083.       for (i = 0; i < LONGSIZE(bss_size); i++)
  5084.     mywrite (&zero, 1, sizeof (long), outdesc);
  5085.     }
  5086.  
  5087.   write_reloc_hunk();
  5088.   write_symbol_hunk(number_of_data_hunk);
  5089.   {
  5090.     long hunk_end = 0x3f2;
  5091.     mywrite(&hunk_end, 1, sizeof(long), outdesc);
  5092.   }
  5093. #endif
  5094. }
  5095.  
  5096. /* Read the data segment contents of ENTRY, relocate them,
  5097.    and write the result to the output file.
  5098.    If `-r', save the data relocation for later reuse.
  5099.    See comments in `copy_text'.  */
  5100.  
  5101. void
  5102. copy_data (entry)
  5103.      struct file_entry *entry;
  5104. {
  5105.   register struct relocation_info *reloc;
  5106.   register char *bytes;
  5107.   register int desc;
  5108.  
  5109.   if (trace_files)
  5110.     prline_file_name (entry, stderr);
  5111.  
  5112.   desc = file_open (entry);
  5113.  
  5114.   bytes = (char *) alloca (entry->data_size);
  5115.  
  5116.   if (entry->datarel) reloc = entry->datarel;
  5117.   else if (output_style == OUTPUT_RELOCATABLE)    /* Will need this again */
  5118.     {
  5119.       read_file_relocation (entry);
  5120.       reloc = entry->datarel;
  5121.     }
  5122.   else
  5123.     {
  5124.       reloc = (struct relocation_info *) alloca (entry->data_reloc_size);
  5125.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  5126.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  5127.     fatal_with_file ("premature eof in data relocation of ", entry);
  5128. #ifdef MACH_O
  5129.       if (entry->file_type == IS_MACH_O)
  5130.     translate_mach_o_relocation (entry, reloc,
  5131.                      entry->data_reloc_size / sizeof (struct relocation_info));
  5132. #endif
  5133.     }
  5134.  
  5135.   lseek (desc, entry->starting_offset + entry->data_offset, L_SET);
  5136.   if (entry->data_size != read (desc, bytes, entry->data_size))
  5137.     fatal_with_file ("premature eof in data section of ", entry);
  5138.  
  5139.   perform_relocation (bytes, entry->data_start_address 
  5140. #ifndef HUNK_INSTEAD_OF_A_OUT
  5141.                         - entry->orig_data_address
  5142. #endif
  5143.                                     ,
  5144.                 entry->data_size, reloc, entry->data_reloc_size, entry);
  5145.  
  5146.   mywrite (bytes, 1, entry->data_size, outdesc);
  5147. }
  5148.  
  5149. /* Relocate ENTRY's text or data section contents.
  5150.    DATA is the address of the contents, in core.
  5151.    DATA_SIZE is the length of the contents.
  5152.    PC_RELOCATION is the difference between the address of the contents
  5153.      in the output file and its address in the input file.
  5154.    RELOC_INFO is the address of the relocation info, in core.
  5155.    RELOC_SIZE is its length in bytes.  */
  5156. /* This version is about to be severly hacked by Randy.  Hope it
  5157.    works afterwards. */
  5158. void
  5159. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  5160.      char *data;
  5161.      struct relocation_info *reloc_info;
  5162.      struct file_entry *entry;
  5163.      int pc_relocation;
  5164.      int data_size;
  5165.      int reloc_size;
  5166. {
  5167.   register struct relocation_info *p = reloc_info;
  5168.   struct relocation_info *end
  5169.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  5170.   int text_relocation = entry->text_start_address - entry->orig_text_address;
  5171.   int data_relocation = entry->data_start_address - entry->orig_data_address;
  5172.   int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
  5173.  
  5174. #ifdef HUNK_INSTEAD_OF_A_OUT
  5175.   int this_hunk;
  5176. #endif
  5177.  
  5178.   for (; p < end; p++)
  5179.     {
  5180.       register int relocation = 0;
  5181.       register int addr = RELOC_ADDRESS(p);
  5182.       register unsigned int mask = 0;
  5183. #ifdef HUNK_INSTEAD_OF_A_OUT
  5184.       int ext_abs;
  5185.       
  5186.       ext_abs = 0;
  5187. #endif
  5188.  
  5189.       if (addr >= data_size)
  5190.     fatal_with_file ("relocation address out of range in ", entry);
  5191.  
  5192.       if (RELOC_EXTERN_P(p))
  5193.     {
  5194.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  5195.       symbol *sp = ((symbol *)
  5196.             (((struct nlist *)
  5197.               (((char *)entry->symbols) + symindex))
  5198.              ->n_un.n_name));
  5199.  
  5200. #ifdef N_INDR
  5201.       /* Resolve indirection */
  5202.       if ((sp->defined & ~N_EXT) == N_INDR)
  5203.         sp = (symbol *) sp->value;
  5204. #endif
  5205.  
  5206.       if (symindex >= entry->syms_size)
  5207.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5208.  
  5209.       /* If the symbol is undefined, leave it at zero.  */
  5210.       if (! sp->defined)
  5211.         relocation = 0;
  5212.       else
  5213.         relocation = sp->value;
  5214.  
  5215. #ifdef HUNK_INSTEAD_OF_A_OUT
  5216.       if ((sp->defined & ~N_EXT) == N_ABS)
  5217.         /* sort of a kludge.. the only external symbol (not pcrelative)
  5218.              * we can really resolve.. */
  5219.         ext_abs = 1;
  5220.       else if ((sp->defined & ~N_EXT) == N_TEXT ||
  5221.           (sp->defined & ~N_EXT) == N_SETT)
  5222.         {
  5223.           this_hunk = number_of_code_hunk;
  5224.           if (RELOC_BASEREL_P (p))
  5225.             {
  5226.               fprintf (stderr, "symn = $%x, extern = %d, addr = $%lx.\n",
  5227.                          p->r_symbolnum, p->r_extern, p->r_address);
  5228.           fatal_with_file ("base relative text relocation in ", entry);
  5229.         }
  5230.         }
  5231.       else if ((sp->defined & ~N_EXT) == N_DATA ||
  5232.                (sp->defined & ~N_EXT) == N_SETD ||
  5233.            (sp->defined & ~N_EXT) == N_SETV)
  5234.         {
  5235.           this_hunk = number_of_data_hunk;
  5236.         }
  5237.       else if ((sp->defined & ~N_EXT) == N_BSS ||
  5238.            (sp->defined & ~N_EXT) == N_UNDF ||
  5239.                (sp->defined & ~N_EXT) == N_SETB)
  5240.         {
  5241.           this_hunk = number_of_bss_hunk;
  5242.         }
  5243.       else    
  5244.         fatal_with_file ("external symbol with unknown type $%x in ", entry, sp->defined);
  5245. #endif
  5246.     }
  5247.       else switch (RELOC_TYPE(p))
  5248.     {
  5249.     case N_TEXT:
  5250.     case N_TEXT | N_EXT:
  5251.       if (RELOC_BASEREL_P (p))
  5252.         {
  5253.           fprintf (stderr, "symn = $%x, extern = %d, addr = $%lx.\n",
  5254.                      p->r_symbolnum, p->r_extern, p->r_address);
  5255.           fatal_with_file ("base relative text relocation in ", entry);
  5256.         }
  5257.       else
  5258.         relocation = text_relocation;
  5259. #ifdef HUNK_INSTEAD_OF_A_OUT
  5260.       this_hunk = number_of_code_hunk;
  5261. #endif
  5262.       break;
  5263.  
  5264.     case N_DATA:
  5265.     case N_DATA | N_EXT:
  5266. #ifdef HUNK_INSTEAD_OF_A_OUT
  5267.       if (RELOC_BASEREL_P (p))
  5268.         relocation = entry->data_start_address;
  5269.       else
  5270. #endif
  5271.         relocation = data_relocation;
  5272. #ifdef HUNK_INSTEAD_OF_A_OUT
  5273.       this_hunk = number_of_data_hunk;
  5274. #endif
  5275.       break;
  5276.  
  5277.     case N_BSS:
  5278.     case N_BSS | N_EXT:
  5279. #ifdef HUNK_INSTEAD_OF_A_OUT
  5280.       if (RELOC_BASEREL_P (p))
  5281.         relocation = entry->bss_start_address - entry->data_size;
  5282.       else
  5283. #endif
  5284.         relocation = bss_relocation;
  5285. #ifdef HUNK_INSTEAD_OF_A_OUT
  5286.       this_hunk = number_of_bss_hunk;
  5287. #endif
  5288.       break;
  5289.  
  5290.     case N_ABS:
  5291.     case N_ABS | N_EXT:
  5292.       /* Don't know why this code would occur, but apparently it does.  */
  5293.       break;
  5294.  
  5295.     default:
  5296.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  5297.     }
  5298.  
  5299. #ifdef HUNK_INSTEAD_OF_A_OUT
  5300.       /* in this case, ONLY relocate those pc-relative 32bit jumps, that
  5301.        * gas generates, since they are position independent, this gives
  5302.        * a HUGE.. 'if' inside of '#ifdef' oh well... */
  5303.       if (RELOC_PCREL_P(p) || RELOC_BASEREL_P(p) || ext_abs) {
  5304.       
  5305.       /* VERY BIG KLUDGE AHEAD! Since this amiga hunk format is really
  5306.        * limited, 8bit and 16bit references are always defined to be
  5307.        * pc-relative (according to the AmigaDOS RM 2nd ed). BUT if such
  5308.        * a symbol is resolved by an absolute symbol then it's not considered
  5309.        * to be pc-relative any more. This is nowhere documented, but you
  5310.        * couldn't get
  5311.        *   jsr _LVOOpen(a6)
  5312.        * to work if you wouldn't do it this way. */
  5313.        if (ext_abs) RELOC_PCREL_P(p) = 0;
  5314.       
  5315. #endif
  5316.       if (RELOC_PCREL_P(p))
  5317.     relocation -= pc_relocation;
  5318.  
  5319.       /* if base relative, subtract 64k/2, so we get a larger range */
  5320.       if (RELOC_BASEREL_P(p))
  5321.     {
  5322.       if (! databss_together)
  5323.         fatal_with_file ("Reloc is base relative. Specify -databss-together in ", entry);
  5324.       relocation -= 0x7ffe;
  5325.     }
  5326.  
  5327. #ifdef RELOC_ADD_EXTRA
  5328.       relocation += RELOC_ADD_EXTRA(p);
  5329.       if (output_style == OUTPUT_RELOCATABLE)
  5330.     {
  5331.       /* If this RELOC_ADD_EXTRA is 0, it means that the
  5332.          symbol was external and the relocation does not
  5333.          need a fixup here.  */
  5334.       if (RELOC_ADD_EXTRA (p))
  5335.         {
  5336.           if (! RELOC_PCREL_P (p))
  5337.         RELOC_ADD_EXTRA (p) = relocation;
  5338.           else
  5339.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5340.         }
  5341. #if 0
  5342.       if (! RELOC_PCREL_P (p))
  5343.         {
  5344.           if ((int)p->r_type <= RELOC_32
  5345.           || RELOC_EXTERN_P (p) == 0)
  5346.         RELOC_ADD_EXTRA (p) = relocation;
  5347.         }
  5348.       else if (RELOC_EXTERN_P (p))
  5349.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5350. #endif
  5351.       continue;
  5352.     }
  5353. #endif
  5354.  
  5355.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  5356.  
  5357.       /* Unshifted mask for relocation */
  5358.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  5359.       mask |= mask - 1;
  5360.       relocation &= mask;
  5361.  
  5362.       /* Shift everything up to where it's going to be used */
  5363.       relocation <<= RELOC_TARGET_BITPOS(p);
  5364.       mask <<= RELOC_TARGET_BITPOS(p);
  5365.       switch (RELOC_TARGET_SIZE(p))
  5366.     {
  5367.     case 0:
  5368.       if (RELOC_MEMORY_SUB_P(p))
  5369.         relocation -= mask & *(char *) (data + addr);
  5370.       else if (RELOC_MEMORY_ADD_P(p))
  5371.         relocation += mask & *(char *) (data + addr);
  5372.       if (relocation < -128 || relocation > 127)
  5373.         fatal_with_file ("Byte reloc overflow in ", entry);
  5374.  
  5375.       *(char *) (data + addr) &= ~mask;
  5376.       *(char *) (data + addr) |= relocation;
  5377.       break;
  5378.  
  5379.     case 1:
  5380.       {
  5381.       int r=relocation;
  5382.  
  5383.       if (RELOC_MEMORY_SUB_P(p))
  5384.         relocation -= mask & *(short *) (data + addr);
  5385.       else if (RELOC_MEMORY_ADD_P(p))
  5386.         relocation += mask & *(short *) (data + addr);
  5387.  
  5388.       if (relocation < -32768 || relocation > 32767)
  5389.         {
  5390.           fprintf (stderr, "relocation = $%lx, bsr = %d, pcr = %d, r= $%lx\n",
  5391.                      relocation, RELOC_BASEREL_P(p), RELOC_PCREL_P (p), r);
  5392.           fprintf (stderr, "textr = $%x, datar = $%x, bssr = $%x\n",
  5393.                      text_relocation, data_relocation, bss_relocation);
  5394.           fprintf (stderr, "symn = $%x, extern = %d, addr = $%lx.\n",
  5395.                      p->r_symbolnum, p->r_extern, p->r_address);
  5396.           fprintf (stderr, "data_size = %d, bss_size = %d.\n",
  5397.                data_size, bss_size);
  5398.           fatal_with_file ("Word reloc overflow in ", entry);
  5399.         }
  5400.  
  5401.       *(short *) (data + addr) &= ~mask;
  5402.       *(short *) (data + addr) |= relocation;
  5403.       break;
  5404.       }
  5405.  
  5406.     case 2:
  5407. #ifdef CROSS_LINKER
  5408.       /* This is necessary if the host has stricter alignment
  5409.          than the target.  Too slow to use all the time.
  5410.          Also doesn't deal with differing byte-order.  */
  5411.       {
  5412.         /* Thing to relocate.  */
  5413.         long thing;
  5414.         bcopy (data + addr, &thing, sizeof (thing));
  5415.         if (RELOC_MEMORY_SUB_P (p))
  5416.           relocation -= mask & thing;
  5417.         else if (RELOC_MEMORY_ADD_P (p))
  5418.           relocation += mask & thing;
  5419.         thing = (thing & ~mask) | relocation;
  5420.         bcopy (&thing, data + addr, sizeof (thing));
  5421.       }
  5422. #else /* not CROSS_LINKER */
  5423.       if (RELOC_MEMORY_SUB_P(p))
  5424.         relocation -= mask & *(long *) (data + addr);
  5425.       else if (RELOC_MEMORY_ADD_P(p))
  5426.         relocation += mask & *(long *) (data + addr);
  5427.  
  5428.       *(long *) (data + addr) &= ~mask;
  5429.       *(long *) (data + addr) |= relocation;
  5430. #endif /* not CROSS_LINKER */
  5431.       break;
  5432.  
  5433.     default:
  5434.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  5435.     }
  5436.  
  5437. #ifdef HUNK_INSTEAD_OF_A_OUT
  5438.     /* now finish this huge 'if' .. */
  5439.     }
  5440.     else
  5441.       {
  5442.         /* this only deals with 32bit relocs, the Amiga-loader
  5443.          * doesn't support 1 or 2 byte relocs, they are only defined
  5444.          * inside program-units (commonly known as object-files:-)) */
  5445.  
  5446.         if (RELOC_TARGET_SIZE(p) != 2)
  5447.           fatal_with_file ("unsupported reloc-size in ", entry);
  5448.  
  5449.         *(long *) (data + addr) += relocation;
  5450.         addr += pc_relocation;
  5451.             add_to_reloc_hunk(this_hunk, addr);
  5452.       }
  5453. #endif
  5454.     }
  5455. }
  5456.  
  5457. /* For OUTPUT_RELOCATABLE only: write out the relocation,
  5458.    relocating the addresses-to-be-relocated.  */
  5459.  
  5460. void coptxtrel (), copdatrel ();
  5461.  
  5462. void
  5463. write_rel ()
  5464. {
  5465.   register int i;
  5466.   register int count = 0;
  5467.  
  5468.   if (trace_files)
  5469.     fprintf (stderr, "Writing text relocation:\n\n");
  5470.  
  5471.   /* Assign each global symbol a sequence number, giving the order
  5472.      in which `write_syms' will write it.
  5473.      This is so we can store the proper symbolnum fields
  5474.      in relocation entries we write.  */
  5475.  
  5476.   for (i = 0; i < TABSIZE; i++)
  5477.     {
  5478.       symbol *sp;
  5479.       for (sp = symtab[i]; sp; sp = sp->link)
  5480.     if (sp->referenced || sp->defined)
  5481.       {
  5482.         sp->def_count = count++;
  5483. #ifndef NeXT
  5484.         /* Leave room for the reference required by N_INDR, if
  5485.            necessary.  */
  5486.         if ((sp->defined & ~N_EXT) == N_INDR)
  5487.           count++;
  5488. #endif
  5489.       }
  5490.     }
  5491.   /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
  5492.      whatever indirect blocks we have.  */
  5493. #ifndef NeXT
  5494.   if (count != defined_global_sym_count
  5495.       + undefined_global_sym_count + global_indirect_count)
  5496. #else
  5497.   if (count != defined_global_sym_count
  5498.       + undefined_global_sym_count)
  5499. #endif
  5500.     fatal ("internal error");
  5501.  
  5502.   /* Write out the relocations of all files, remembered from copy_text.  */
  5503.  
  5504.   lseek (outdesc, output_trel_offset, 0);
  5505.   each_full_file (coptxtrel, 0);
  5506.  
  5507.   if (trace_files)
  5508.     fprintf (stderr, "\nWriting data relocation:\n\n");
  5509.  
  5510.   lseek (outdesc, output_drel_offset, 0);
  5511.   each_full_file (copdatrel, 0);
  5512.  
  5513.   if (trace_files)
  5514.     fprintf (stderr, "\n");
  5515. }
  5516.  
  5517. void
  5518. coptxtrel (entry)
  5519.      struct file_entry *entry;
  5520. {
  5521.   register struct relocation_info *p, *end;
  5522.   register int reloc = entry->text_start_address - text_start;
  5523.  
  5524.   p = entry->textrel;
  5525.   end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
  5526.   while (p < end)
  5527.     {
  5528.       RELOC_ADDRESS(p) += reloc;
  5529.       if (RELOC_EXTERN_P(p))
  5530.     {
  5531.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5532.       symbol *symptr = ((symbol *)
  5533.                 (((struct nlist *)
  5534.                   (((char *)entry->symbols) + symindex))
  5535.                  ->n_un.n_name));
  5536.  
  5537.       if (symindex >= entry->syms_size)
  5538.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5539.  
  5540. #ifdef N_INDR
  5541.       /* Resolve indirection.  */
  5542.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5543.         symptr = (symbol *) symptr->value;
  5544. #endif
  5545.  
  5546.       /* If the symbol is now defined, change the external relocation
  5547.          to an internal one.  */
  5548.  
  5549.       if (symptr->defined)
  5550.         {
  5551.           RELOC_EXTERN_P(p) = 0;
  5552.           RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
  5553. #ifdef RELOC_ADD_EXTRA
  5554.           /* If we aren't going to be adding in the value in
  5555.              memory on the next pass of the loader, then we need
  5556.          to add it in from the relocation entry.  Otherwise
  5557.              the work we did in this pass is lost.  */
  5558.           if (!RELOC_MEMORY_ADD_P(p))
  5559.         RELOC_ADD_EXTRA (p) += symptr->value;
  5560. #endif
  5561.         }
  5562.       else
  5563.         /* Debugger symbols come first, so have to start this
  5564.            after them.  */
  5565. #ifndef NeXT
  5566.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5567.                  - defined_global_sym_count
  5568.                  - undefined_global_sym_count
  5569.                  - global_indirect_count);
  5570. #else
  5571.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5572.                  - defined_global_sym_count
  5573.                  - undefined_global_sym_count);
  5574. #endif
  5575.     }
  5576.       p++;
  5577.     }
  5578.  
  5579. #ifdef MACH_O
  5580.   if (output_file_type == IS_MACH_O)
  5581.     generate_mach_o_relocations(entry->textrel,
  5582.                 entry->text_reloc_size / sizeof (struct relocation_info));
  5583. #endif
  5584.  
  5585.   mywrite (entry->textrel, 1, entry->text_reloc_size, outdesc);
  5586. }
  5587.  
  5588. void
  5589. copdatrel (entry)
  5590.      struct file_entry *entry;
  5591. {
  5592.   register struct relocation_info *p, *end;
  5593.   /* Relocate the address of the relocation.
  5594.      Old address is relative to start of the input file's data section.
  5595.      New address is relative to start of the output file's data section.
  5596.  
  5597.      So the amount we need to relocate it by is the offset of this
  5598.      input file's data section within the output file's data section.  */
  5599.   register int reloc = entry->data_start_address - data_start;
  5600.  
  5601.   p = entry->datarel;
  5602.   end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
  5603.   while (p < end)
  5604.     {
  5605.       RELOC_ADDRESS(p) += reloc;
  5606.       if (RELOC_EXTERN_P(p))
  5607.     {
  5608.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5609.       symbol *symptr = ((symbol *)
  5610.                 (((struct nlist *)
  5611.                   (((char *)entry->symbols) + symindex))
  5612.                  ->n_un.n_name));
  5613.       int symtype;
  5614.  
  5615.       if (symindex >= entry->syms_size)
  5616.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5617.  
  5618. #ifdef N_INDR
  5619.       /* Resolve indirection.  */
  5620.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5621.         symptr = (symbol *) symptr->value;
  5622. #endif
  5623.  
  5624.       symtype = symptr->defined & ~N_EXT;
  5625.  
  5626.       if (force_common_definition
  5627.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  5628.         {
  5629.           RELOC_EXTERN_P(p) = 0;
  5630.           RELOC_SYMBOL(p) = symtype;
  5631.         }
  5632.       else
  5633.         /* Debugger symbols come first, so have to start this
  5634.            after them.  */
  5635. #ifndef NeXT
  5636.         RELOC_SYMBOL(p)
  5637.           = (((symbol *)
  5638.           (((struct nlist *)
  5639.             (((char *)entry->symbols) + symindex))
  5640.            ->n_un.n_name))
  5641.          ->def_count
  5642.          + nsyms - defined_global_sym_count
  5643.          - undefined_global_sym_count
  5644.          - global_indirect_count);
  5645. #else
  5646.         RELOC_SYMBOL(p)
  5647.           = (((symbol *)
  5648.           (((struct nlist *)
  5649.             (((char *)entry->symbols) + symindex))
  5650.            ->n_un.n_name))
  5651.          ->def_count
  5652.          + nsyms - defined_global_sym_count
  5653.          - undefined_global_sym_count);
  5654. #endif
  5655.     }
  5656.       p++;
  5657.     }
  5658. #ifdef MACH_O
  5659.   if (output_file_type == IS_MACH_O)
  5660.     generate_mach_o_relocations(entry->datarel,
  5661.                 entry->data_reloc_size / sizeof (struct relocation_info));
  5662. #endif
  5663.  
  5664.   mywrite (entry->datarel, 1, entry->data_reloc_size, outdesc);
  5665. }
  5666.  
  5667. void write_file_syms ();
  5668. void write_string_table ();
  5669.  
  5670. /* Total size of string table strings allocated so far,
  5671.    including strings in `strtab_vector'.  */
  5672. int strtab_size;
  5673.  
  5674. /* Vector whose elements are strings to be added to the string table.  */
  5675. char **strtab_vector;
  5676.  
  5677. /* Vector whose elements are the lengths of those strings.  */
  5678. int *strtab_lens;
  5679.  
  5680. /* Index in `strtab_vector' at which the next string will be stored.  */
  5681. int strtab_index;
  5682.  
  5683. /* Add the string NAME to the output file string table.
  5684.    Record it in `strtab_vector' to be output later.
  5685.    Return the index within the string table that this string will have.  */
  5686.  
  5687. int
  5688. assign_string_table_index (name)
  5689.      char *name;
  5690. {
  5691.   register int index = strtab_size;
  5692.   register int len = strlen (name) + 1;
  5693.  
  5694.   strtab_size += len;
  5695.   strtab_vector[strtab_index] = name;
  5696.   strtab_lens[strtab_index++] = len;
  5697.  
  5698.   return index;
  5699. }
  5700.  
  5701. FILE *outstream = (FILE *) 0;
  5702.  
  5703. /* Write the contents of `strtab_vector' into the string table.
  5704.    This is done once for each file's local&debugger symbols
  5705.    and once for the global symbols.  */
  5706.  
  5707. void
  5708. write_string_table ()
  5709. {
  5710.   register int i;
  5711.  
  5712.   lseek (outdesc, output_strs_offset + output_strs_size, 0);
  5713.  
  5714.   if (!outstream)
  5715.     outstream = fdopen (outdesc, "w");
  5716.  
  5717.   for (i = 0; i < strtab_index; i++)
  5718.     {
  5719.       fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
  5720.       output_strs_size += strtab_lens[i];
  5721.     }
  5722.  
  5723.   fflush (outstream);
  5724.  
  5725.   /* Report I/O error such as disk full.  */
  5726.   if (ferror (outstream))
  5727.     perror_name (output_filename);
  5728. }
  5729.  
  5730. /* Write the symbol table and string table of the output file.  */
  5731.  
  5732. void
  5733. write_syms ()
  5734. {
  5735.   /* Number of symbols written so far.  */
  5736.   int syms_written = 0;
  5737.   register int i;
  5738.   register symbol *sp;
  5739.  
  5740.   /* Buffer big enough for all the global symbols.  One
  5741.      extra struct for each indirect symbol to hold the extra reference
  5742.      following. */
  5743.   struct nlist *buf
  5744. #ifndef NeXT
  5745.     = (struct nlist *) alloca ((defined_global_sym_count
  5746.                 + undefined_global_sym_count
  5747.                 + global_indirect_count)
  5748.                    * sizeof (struct nlist));
  5749. #else
  5750.     = (struct nlist *) alloca ((defined_global_sym_count
  5751.                 + undefined_global_sym_count)
  5752.                    * sizeof (struct nlist));
  5753. #endif
  5754.   /* Pointer for storing into BUF.  */
  5755.   register struct nlist *bufp = buf;
  5756.  
  5757. #ifdef HUNK_INSTEAD_OF_A_OUT
  5758.   /* this enables us to output "regular" amiga symbols without
  5759.    * the BSD-like debug-hunk */
  5760.   if (number_of_debug_hunk == -1) return;
  5761. #endif
  5762.  
  5763.   /* Size of string table includes the bytes that store the size.  */
  5764.   strtab_size = sizeof strtab_size;
  5765.  
  5766.   output_syms_size = 0;
  5767.   output_strs_size = strtab_size;
  5768.  
  5769.   if (strip_symbols == STRIP_ALL)
  5770.     return;
  5771.  
  5772.   /* Write the local symbols defined by the various files.  */
  5773.  
  5774.   each_file (write_file_syms, &syms_written);
  5775.   file_close ();
  5776.  
  5777.   /* Now write out the global symbols.  */
  5778.  
  5779.   /* Allocate two vectors that record the data to generate the string
  5780.      table from the global symbols written so far.  This must include
  5781.      extra space for the references following indirect outputs. */
  5782.  
  5783.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  5784.                      + global_indirect_count) * sizeof (char *));
  5785.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  5786.                  + global_indirect_count) * sizeof (int));
  5787.   strtab_index = 0;
  5788.  
  5789.   /* Scan the symbol hash table, bucket by bucket.  */
  5790.  
  5791.   for (i = 0; i < TABSIZE; i++)
  5792.     for (sp = symtab[i]; sp; sp = sp->link)
  5793.       {
  5794.     struct nlist nl;
  5795.  
  5796. #ifdef N_SECT
  5797.     nl.n_sect = 0;
  5798. #else
  5799.     nl.n_other = 0;
  5800. #endif
  5801.     nl.n_desc = 0;
  5802.  
  5803.     /* Compute a `struct nlist' for the symbol.  */
  5804.  
  5805.     if (sp->defined || sp->referenced)
  5806.       {
  5807.         /* common condition needs to be before undefined condition */
  5808.         /* because unallocated commons are set undefined in */
  5809.         /* digest_symbols */
  5810.         if (sp->defined > 1) /* defined with known type */
  5811.           {
  5812.         /* If the target of an indirect symbol has been
  5813.            defined and we are outputting an executable,
  5814.            resolve the indirection; it's no longer needed */
  5815.         if (output_style != OUTPUT_RELOCATABLE
  5816.             && ((sp->defined & ~N_EXT) == N_INDR)
  5817.             && (((symbol *) sp->value)->defined > 1))
  5818.           {
  5819.             symbol *newsp = (symbol *) sp->value;
  5820.             nl.n_type = newsp->defined;
  5821.             nl.n_value = newsp->value;
  5822.           }
  5823.         else
  5824.           {
  5825.             nl.n_type = sp->defined;
  5826.             if (sp->defined != (N_INDR | N_EXT))
  5827.               nl.n_value = sp->value;
  5828.             else
  5829.               nl.n_value = 0;
  5830.           }
  5831.           }
  5832.         else if (sp->max_common_size) /* defined as common but not allocated. */
  5833.           {
  5834.         /* happens only with -r and not -d */
  5835.         /* write out a common definition */
  5836.         nl.n_type = N_UNDF | N_EXT;
  5837.         nl.n_value = sp->max_common_size;
  5838.           }
  5839.         else if (!sp->defined)          /* undefined -- legit only if -r */
  5840.           {
  5841.         nl.n_type = N_UNDF | N_EXT;
  5842.         nl.n_value = 0;
  5843.           }
  5844.         else
  5845.           fatal ("internal error: %s defined in mysterious way", sp->name);
  5846.  
  5847.         /* Allocate string table space for the symbol name.  */
  5848.  
  5849.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  5850.  
  5851.         /* Output to the buffer and count it.  */
  5852.  
  5853.         *bufp++ = nl;
  5854.         syms_written++;
  5855.         if (nl.n_type == (N_INDR | N_EXT))
  5856. #ifndef NeXT
  5857.           {
  5858.         struct nlist xtra_ref;
  5859.         xtra_ref.n_type == N_EXT | N_UNDF;
  5860.         xtra_ref.n_un.n_strx
  5861.           = assign_string_table_index (((symbol *) sp->value)->name);
  5862. #ifdef N_SECT
  5863.         xtra_ref.n_sect = 0;
  5864. #else
  5865.         xtra_ref.n_other = 0;
  5866. #endif
  5867.         xtra_ref.n_desc = 0;
  5868.         xtra_ref.n_value = 0;
  5869.         *bufp++ = xtra_ref;
  5870.         syms_written++;
  5871.           }
  5872. #else
  5873.         nl.n_value = assign_string_table_index (((symbol *) sp->value)->name);
  5874. #endif
  5875.       }
  5876.       }
  5877.  
  5878. #ifdef MACH_O
  5879.   if (output_file_type == IS_MACH_O)
  5880.     generate_mach_o_symbols(buf, bufp - buf);
  5881. #endif
  5882.  
  5883.   /* Output the buffer full of `struct nlist's.  */
  5884.  
  5885.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5886.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5887.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5888.  
  5889.   if (syms_written != nsyms)
  5890.     fatal ("internal error: wrong number of symbols written into output file", 0);
  5891.  
  5892.   /* Now the total string table size is known, so write it into the
  5893.      first word of the string table.  */
  5894.  
  5895.   lseek (outdesc, output_strs_offset, 0);
  5896.   mywrite (&strtab_size, sizeof (int), 1, outdesc);
  5897.  
  5898.   /* Write the strings for the global symbols.  */
  5899.  
  5900.   write_string_table ();
  5901. }
  5902.  
  5903. /* Write the local and debugger symbols of file ENTRY.
  5904.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  5905.  
  5906. /* Note that we do not combine identical names of local symbols.
  5907.    dbx or gdb would be confused if we did that.  */
  5908.  
  5909. void
  5910. write_file_syms (entry, syms_written_addr)
  5911.      struct file_entry *entry;
  5912.      int *syms_written_addr;
  5913. {
  5914.   register struct nlist *p = entry->symbols;
  5915.   register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
  5916.  
  5917.   /* Buffer to accumulate all the syms before writing them.
  5918.      It has one extra slot for the local symbol we generate here.  */
  5919.   struct nlist *buf
  5920.     = (struct nlist *) alloca (entry->syms_size + sizeof (struct nlist));
  5921.   register struct nlist *bufp = buf;
  5922.  
  5923.   /* Upper bound on number of syms to be written here.  */
  5924.   int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
  5925.  
  5926.   /* Make tables that record, for each symbol, its name and its name's length.
  5927.      The elements are filled in by `assign_string_table_index'.  */
  5928.  
  5929.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  5930.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  5931.   strtab_index = 0;
  5932.  
  5933.   /* Generate a local symbol for the start of this file's text.  */
  5934.  
  5935.   if (discard_locals != DISCARD_ALL)
  5936.     {
  5937.       struct nlist nl;
  5938.  
  5939.       nl.n_type = N_TEXT;
  5940.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  5941.       nl.n_value = entry->text_start_address;
  5942.       nl.n_desc = 0;
  5943. #ifdef N_SECT
  5944.       nl.n_sect = 0;
  5945. #else
  5946.       nl.n_other = 0;
  5947. #endif
  5948.       *bufp++ = nl;
  5949.       (*syms_written_addr)++;
  5950.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  5951.     }
  5952.  
  5953.   /* Read the file's string table.  */
  5954.  
  5955.   entry->strings = (char *) alloca (entry->strs_size);
  5956.   read_entry_strings (file_open (entry), entry);
  5957.  
  5958.   for (; p < end; p++)
  5959.     {
  5960.       register int type = p->n_type;
  5961.       register int write = 0;
  5962.  
  5963.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  5964.  
  5965.  
  5966.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  5967.                 /* types of symbols are never written */
  5968.                 /* globally, though they are stored */
  5969.                 /* globally.  */
  5970.         write = output_style == OUTPUT_RELOCATABLE;
  5971.       else if (!(type & (N_STAB | N_EXT)))
  5972.         /* ordinary local symbol */
  5973.     write = ((discard_locals != DISCARD_ALL)
  5974.          && !(discard_locals == DISCARD_L &&
  5975.               (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  5976.          && type != N_WARNING);
  5977.       else if (!(type & N_EXT))
  5978.     /* debugger symbol */
  5979.         write = (strip_symbols == STRIP_NONE);
  5980.  
  5981.       if (write)
  5982.     {
  5983.       /* If this symbol has a name,
  5984.          allocate space for it in the output string table.  */
  5985.  
  5986.       if (p->n_un.n_strx)
  5987.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  5988.                             + entry->strings);
  5989.  
  5990.       /* Output this symbol to the buffer and count it.  */
  5991.  
  5992.       *bufp++ = *p;
  5993.       (*syms_written_addr)++;
  5994.     }
  5995.     }
  5996.  
  5997. #ifdef MACH_O
  5998.   if (output_file_type == IS_MACH_O)
  5999.     generate_mach_o_symbols(buf, bufp - buf);
  6000. #endif
  6001.  
  6002.   /* All the symbols are now in BUF; write them.  */
  6003.  
  6004.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  6005.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  6006.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  6007.  
  6008.   /* Write the string-table data for the symbols just written,
  6009.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  6010.  
  6011.   write_string_table ();
  6012.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  6013. }
  6014.  
  6015. /* Copy any GDB symbol segments from the input files to the output file.
  6016.    The contents of the symbol segment is copied without change
  6017.    except that we store some information into the beginning of it.  */
  6018.  
  6019. void write_file_symseg ();
  6020.  
  6021. void
  6022. write_symsegs ()
  6023. {
  6024.   lseek (outdesc, output_symseg_offset, 0);
  6025.   each_file (write_file_symseg, 0);
  6026. }
  6027.  
  6028. void
  6029. write_file_symseg (entry)
  6030.      struct file_entry *entry;
  6031. {
  6032.   char buffer[4096];
  6033.   struct symbol_root root;
  6034.   int indesc, len, total;
  6035.  
  6036.   if (entry->symseg_size == 0)
  6037.     return;
  6038.  
  6039.   output_symseg_size += entry->symseg_size;
  6040.  
  6041.   /* This entry has a symbol segment.  Read the root of the segment.  */
  6042.  
  6043.   indesc = file_open (entry);
  6044.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  6045.   if (sizeof root != read (indesc, &root, sizeof root))
  6046.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  6047.  
  6048.   /* Store some relocation info into the root.  */
  6049.  
  6050.   root.ldsymoff = entry->local_syms_offset;
  6051.   root.textrel = entry->text_start_address - entry->orig_text_address;
  6052.   root.datarel = entry->data_start_address - entry->orig_data_address;
  6053.   root.bssrel = entry->bss_start_address - entry->orig_bss_address;
  6054.   root.databeg = entry->data_start_address - root.datarel;
  6055.   root.bssbeg = entry->bss_start_address - root.bssrel;
  6056.  
  6057.   /* Write the modified root into the output file.  */
  6058.  
  6059.   mywrite (&root, sizeof root, 1, outdesc);
  6060.  
  6061.   /* Copy the rest of the symbol segment unchanged.  */
  6062.  
  6063.   total = entry->symseg_size - sizeof root;
  6064.  
  6065.   while (total > 0)
  6066.     {
  6067.       len = read (indesc, buffer, min (sizeof buffer, total));
  6068.  
  6069.       if (len != min (sizeof buffer, total))
  6070.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  6071.       total -= len;
  6072.       mywrite (buffer, len, 1, outdesc);
  6073.     }
  6074.  
  6075.   file_close ();
  6076. }
  6077.  
  6078. /* Define a special symbol (etext, edata, or end).  NAME is the
  6079.    name of the symbol, with a leading underscore (whether or not this
  6080.    system uses such underscores).  TYPE is its type (e.g. N_DATA | N_EXT).
  6081.    Store a symbol * for the symbol in *SYM if SYM is non-NULL.  */
  6082. static void
  6083. symbol_define (name, type, sym)
  6084.      /* const */ char *name;
  6085.      int type;
  6086.      symbol **sym;
  6087. {
  6088.   symbol *thesym;
  6089.  
  6090. #if defined(nounderscore)
  6091.   /* Skip the leading underscore.  */
  6092.   name++;
  6093. #endif
  6094.  
  6095.   thesym = getsym (name);
  6096.   if (thesym->defined)
  6097.     {
  6098.       /* The symbol is defined in some input file.  Don't mess with it.  */
  6099.       if (sym)
  6100.     *sym = 0;
  6101.     }
  6102.   else
  6103.     {
  6104.       if (thesym->referenced)
  6105.     /* The symbol was not defined, and we are defining it now.  */
  6106.     undefined_global_sym_count--;
  6107.       thesym->defined = type;
  6108.       thesym->referenced = 1;
  6109.       if (sym)
  6110.     *sym = thesym;
  6111.     }
  6112. }
  6113.  
  6114. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  6115.  
  6116. void
  6117. symtab_init ()
  6118. {
  6119.   symbol_define ("_edata", N_DATA | N_EXT, &edata_symbol);
  6120.   symbol_define ("_etext", N_TEXT | N_EXT, &etext_symbol);
  6121.   symbol_define ("_end", N_BSS | N_EXT, &end_symbol);
  6122.  
  6123.   /* Either _edata or __edata (C names) is OK as far as ANSI is concerned
  6124.      (see section 4.1.2.1).  In general, it is best to use __foo and
  6125.      not worry about the confusing rules for the _foo namespace.
  6126.      But HPUX 7.0 uses _edata, so we might as weel be consistent.  */
  6127.   symbol_define ("__edata", N_DATA | N_EXT, &edata_symbol_alt);
  6128.   symbol_define ("__etext", N_TEXT | N_EXT, &etext_symbol_alt);
  6129.   symbol_define ("__end", N_BSS | N_EXT, &end_symbol_alt);
  6130.  
  6131. #ifdef amigados
  6132.   if (output_datadata_relocs)
  6133.     symbol_define ("___datadata_relocs", N_TEXT | N_EXT, &datadata_reloc_symbol);
  6134.  
  6135.   symbol_define ("__sdata", N_DATA | N_EXT, &sdata_symbol);
  6136.   symbol_define ("___text_size", N_ABS | N_EXT, &text_size_symbol);
  6137.   symbol_define ("___data_size", N_ABS | N_EXT, &data_size_symbol);
  6138.   symbol_define ("___bss_size", N_ABS | N_EXT, &bss_size_symbol);
  6139.   {
  6140.     symbol *a_symbol;
  6141.     symbol_define ("___machtype", N_ABS | N_EXT, &a_symbol);
  6142.     if (a_symbol)
  6143.       a_symbol->value = amiga_machtype;
  6144.       
  6145.     symbol_define ("___databss_together", N_ABS | N_EXT, &a_symbol);
  6146.     if (a_symbol)
  6147.       a_symbol->value = databss_together;
  6148.       
  6149.     if (databss_together)
  6150.       {
  6151.         symbol_define ("___a4_init", N_DATA | N_EXT, &a_symbol);
  6152.         if (a_symbol)
  6153.           a_symbol->value = data_start + 0x7ffe;
  6154.       }
  6155.   }
  6156. #endif
  6157. #ifdef sun
  6158.   {
  6159.     symbol *dynamic_symbol;
  6160.     symbol_define ("__DYNAMIC", N_ABS | N_EXT, &dynamic_symbol);
  6161.     if (dynamic_symbol)
  6162.       dynamic_symbol->value = 0;
  6163.   }
  6164. #endif
  6165. #ifdef sequent
  6166.   {
  6167.     symbol *i387_flt_symbol;
  6168.     symbol_define ("_387_flt", N_ABS | N_EXT, &i387_flt_symbol);
  6169.     if (i387_flt_symbol)
  6170.       i387_flt_symbol->value = 0;
  6171.   }
  6172. #endif
  6173. #ifdef NeXT
  6174.   {
  6175.     symbol *shlib_init_symbol;
  6176.     symbol_define ("__shared_library_initialization", N_UNDF | N_EXT, &shlib_init_symbol);
  6177.     if (shlib_init_symbol)
  6178.       shlib_init_symbol->max_common_size = sizeof (long int);
  6179.   }
  6180. #endif
  6181. }
  6182.  
  6183. /* Compute the hash code for symbol name KEY.  */
  6184.  
  6185. int
  6186. hash_string (key)
  6187.      char *key;
  6188. {
  6189.   register char *cp;
  6190.   register int k;
  6191.  
  6192.   cp = key;
  6193.   k = 0;
  6194.   while (*cp)
  6195.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  6196.  
  6197.   return k;
  6198. }
  6199.  
  6200. /* Get the symbol table entry for the global symbol named KEY.
  6201.    Create one if there is none.  */
  6202.  
  6203. symbol *
  6204. getsym (key)
  6205.      char *key;
  6206. {
  6207.   register int hashval;
  6208.   register symbol *bp;
  6209.  
  6210.   /* Determine the proper bucket.  */
  6211.  
  6212.   hashval = hash_string (key) % TABSIZE;
  6213.  
  6214.   /* Search the bucket.  */
  6215.  
  6216.   for (bp = symtab[hashval]; bp; bp = bp->link)
  6217.     if (! strcmp (key, bp->name))
  6218.       return bp;
  6219.  
  6220.   /* Nothing was found; create a new symbol table entry.  */
  6221.  
  6222.   bp = (symbol *) xmalloc (sizeof (symbol));
  6223.   bp->refs = 0;
  6224.   bp->name = (char *) xmalloc (strlen (key) + 1);
  6225.   strcpy (bp->name, key);
  6226.   bp->defined = 0;
  6227.   bp->referenced = 0;
  6228.   bp->trace = 0;
  6229.   bp->value = 0;
  6230.   bp->max_common_size = 0;
  6231.   bp->warning = 0;
  6232.   bp->undef_refs = 0;
  6233.   bp->multiply_defined = 0;
  6234.  
  6235.   /* Add the entry to the bucket.  */
  6236.  
  6237.   bp->link = symtab[hashval];
  6238.   symtab[hashval] = bp;
  6239.  
  6240.   ++num_hash_tab_syms;
  6241.  
  6242.   return bp;
  6243. }
  6244.  
  6245. /* Like `getsym' but return 0 if the symbol is not already known.  */
  6246.  
  6247. symbol *
  6248. getsym_soft (key)
  6249.      char *key;
  6250. {
  6251.   register int hashval;
  6252.   register symbol *bp;
  6253.  
  6254.   /* Determine which bucket.  */
  6255.  
  6256.   hashval = hash_string (key) % TABSIZE;
  6257.  
  6258.   /* Search the bucket.  */
  6259.  
  6260.   for (bp = symtab[hashval]; bp; bp = bp->link)
  6261.     if (! strcmp (key, bp->name))
  6262.       return bp;
  6263.  
  6264.   return 0;
  6265. }
  6266.  
  6267. /* Report a usage error.
  6268.    Like fatal except prints a usage summary.  */
  6269.  
  6270. void
  6271. usage (string, arg)
  6272.      char *string, *arg;
  6273. {
  6274.   if (string)
  6275.     {
  6276.       fprintf (stderr, "%s: ", progname);
  6277.       fprintf (stderr, string, arg);
  6278.       fprintf (stderr, "\n");
  6279.     }
  6280. #ifdef HUNK_INSTEAD_OF_A_OUT
  6281.   fprintf (stderr, "\
  6282. Usage: %s [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
  6283.        [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
  6284.        [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
  6285.        [-S] [-T[{text,data}] addr] [-V prefix] [-X] \n\
  6286.        [{-a,-amiga-debug-hunk}] [file...]\n",
  6287.        progname);
  6288. #else
  6289.   fprintf (stderr, "\
  6290. Usage: %s [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
  6291.        [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
  6292.        [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
  6293.        [-S] [-T[{text,data}] addr] [-V prefix] [-X] [file...]\n",
  6294.        progname);
  6295. #endif
  6296.   exit (1);
  6297. }
  6298.  
  6299. /* Report a fatal error.
  6300.    STRING is a printf format string and ARG is one arg for it.  */
  6301.  
  6302. void
  6303. fatal (string, arg)
  6304.      char *string, *arg;
  6305. {
  6306.   fprintf (stderr, "%s: ", progname);
  6307.   fprintf (stderr, string, arg);
  6308.   fprintf (stderr, "\n");
  6309.   exit (1);
  6310. }
  6311.  
  6312. /* Report a fatal error.  The error message is STRING
  6313.    followed by the filename of ENTRY.  */
  6314.  
  6315. void
  6316. fatal_with_file (string, entry, arg)
  6317.      char *string;
  6318.      struct file_entry *entry;
  6319. {
  6320.   fprintf (stderr, "%s: ", progname);
  6321.   fprintf (stderr, string, arg);
  6322.   print_file_name (entry, stderr);
  6323.   fprintf (stderr, "\n");
  6324.   exit (1);
  6325. }
  6326.  
  6327. /* Report a fatal error using the message for the last failed system call,
  6328.    followed by the string NAME.  */
  6329.  
  6330. void
  6331. perror_name (name)
  6332.      char *name;
  6333. {
  6334.   extern int errno, sys_nerr;
  6335.   char *s;
  6336.  
  6337.   if (errno < sys_nerr)
  6338.     s = concat ("", strerror (errno), " for %s");
  6339.   else
  6340.     s = "cannot open %s";
  6341.   fatal (s, name);
  6342. }
  6343.  
  6344. /* Report a fatal error using the message for the last failed system call,
  6345.    followed by the name of file ENTRY.  */
  6346.  
  6347. void
  6348. perror_file (entry)
  6349.      struct file_entry *entry;
  6350. {
  6351.   extern int errno, sys_nerr;
  6352.   char *s;
  6353.  
  6354.   if (errno < sys_nerr)
  6355.     s = concat ("", strerror (errno), " for ");
  6356.   else
  6357.     s = "cannot open ";
  6358.   fatal_with_file (s, entry);
  6359. }
  6360.  
  6361. /* Report a nonfatal error.
  6362.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  6363.  
  6364. void
  6365. error (string, arg1, arg2, arg3)
  6366.      char *string, *arg1, *arg2, *arg3;
  6367. {
  6368.   fprintf (stderr, "%s: ", progname);
  6369.   fprintf (stderr, string, arg1, arg2, arg3);
  6370.   fprintf (stderr, "\n");
  6371. }
  6372.  
  6373.  
  6374. /* Output COUNT*ELTSIZE bytes of data at BUF
  6375.    to the descriptor DESC.  */
  6376.  
  6377. void
  6378. mywrite (buf, count, eltsize, desc)
  6379.      char *buf;
  6380.      int count;
  6381.      int eltsize;
  6382.      int desc;
  6383. {
  6384.   register int val;
  6385.   register int bytes = count * eltsize;
  6386.  
  6387.   while (bytes > 0)
  6388.     {
  6389.       val = write (desc, buf, bytes);
  6390.       if (val <= 0)
  6391.     perror_name (output_filename);
  6392.       buf += val;
  6393.       bytes -= val;
  6394.     }
  6395. }
  6396.  
  6397. /* Output PADDING zero-bytes to descriptor OUTDESC.
  6398.    PADDING may be negative; in that case, do nothing.  */
  6399.  
  6400. void
  6401. padfile (padding, outdesc)
  6402.      int padding;
  6403.      int outdesc;
  6404. {
  6405.   register char *buf;
  6406.   if (padding <= 0)
  6407.     return;
  6408.  
  6409.   buf = (char *) alloca (padding);
  6410.   bzero (buf, padding);
  6411.   mywrite (buf, padding, 1, outdesc);
  6412. }
  6413.  
  6414. /* Return a newly-allocated string
  6415.    whose contents concatenate the strings S1, S2, S3.  */
  6416.  
  6417. char *
  6418. concat (s1, s2, s3)
  6419.      char *s1, *s2, *s3;
  6420. {
  6421.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  6422.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  6423.  
  6424.   strcpy (result, s1);
  6425.   strcpy (result + len1, s2);
  6426.   strcpy (result + len1 + len2, s3);
  6427.   result[len1 + len2 + len3] = 0;
  6428.  
  6429.   return result;
  6430. }
  6431.  
  6432. /* Parse the string ARG using scanf format FORMAT, and return the result.
  6433.    If it does not parse, report fatal error
  6434.    generating the error message using format string ERROR and ARG as arg.  */
  6435.  
  6436. int
  6437. parse (arg, format, error)
  6438.      char *arg, *format;
  6439. {
  6440.   int x;
  6441.   if (1 != sscanf (arg, format, &x))
  6442.     fatal (error, arg);
  6443.   return x;
  6444. }
  6445.  
  6446. /* Like malloc but get fatal error if memory is exhausted.  */
  6447.  
  6448. char *
  6449. xmalloc (size)
  6450.      int size;
  6451. {
  6452.   register char *result = malloc (size);
  6453.   if (!result && size)
  6454.     fatal ("virtual memory exhausted", 0);
  6455.   return result;
  6456. }
  6457.  
  6458. /* Like realloc but get fatal error if memory is exhausted.  */
  6459.  
  6460. char *
  6461. xrealloc (ptr, size)
  6462.      char *ptr;
  6463.      int size;
  6464. {
  6465.   register char *result = realloc (ptr, size);
  6466.   if (!result)
  6467.     fatal ("virtual memory exhausted", 0);
  6468.   return result;
  6469. }
  6470.  
  6471. #ifdef USG
  6472.  
  6473. void
  6474. bzero (p, n)
  6475.      char *p;
  6476. {
  6477.   memset (p, 0, n);
  6478. }
  6479.  
  6480. void
  6481. bcopy (from, to, n)
  6482.      char *from, *to;
  6483. {
  6484.   memcpy (to, from, n);
  6485. }
  6486.  
  6487. getpagesize ()
  6488. {
  6489.   return (4096);
  6490. }
  6491.  
  6492. #endif
  6493.  
  6494. #if defined(sun) && defined(sparc)
  6495. int
  6496. getpagesize ()
  6497. {
  6498.   return 8192;
  6499. }
  6500. #endif
  6501.  
  6502. #ifdef HUNK_INSTEAD_OF_A_OUT
  6503. /* the whole rest of the file is used for managment of hunks and subhunks.. */
  6504.  
  6505. /* this is the amiga-equivalent of struct exec */
  6506. struct simple_hunk_header {
  6507.   long    id,    /* this will be 0x3f3 */
  6508.     zero,
  6509.     table_size,
  6510.     first_hunk,
  6511.     last_hunk,
  6512.     sizes[4];   /* there can be at most a code,data,bss & debug hunk */
  6513. };
  6514.  
  6515. /* this writes out a hunk header, depending on the information collected
  6516.  * so far, it will only create hunks, that really exist, so if your data-
  6517.  * size is zero, you won't get a data-hunk at all. */
  6518.  
  6519. void
  6520. write_hunk_header(outfd)
  6521.     int outfd;
  6522. {
  6523.   struct simple_hunk_header sh;
  6524.   int this_hunk, header_size;
  6525.  
  6526.   sh.id = 0x3f3;    /* HUNK_HEADER */
  6527.   sh.zero = 0;
  6528.   sh.table_size = current_hunk;
  6529.   sh.first_hunk = 0;
  6530.   sh.last_hunk  = current_hunk - 1;
  6531.  
  6532.   this_hunk = 0;
  6533.   if (number_of_code_hunk != -1)
  6534.      sh.sizes[this_hunk++] = LONGSIZE(text_size);
  6535.  
  6536.   if (number_of_data_hunk != -1)
  6537.      sh.sizes[this_hunk++] = databss_together 
  6538.                  ? LONGSIZE(data_size + bss_size) : LONGSIZE(data_size);
  6539.  
  6540.   if (!databss_together && number_of_bss_hunk  != -1)
  6541.      sh.sizes[this_hunk++] = LONGSIZE(bss_size);
  6542.  
  6543.   if (number_of_debug_hunk != -1)
  6544.      sh.sizes[this_hunk++] = 0;  /* to be filled in later */
  6545.  
  6546.   header_size = sizeof(sh) - (4-this_hunk)*sizeof(long);
  6547.   mywrite(&sh, 1, header_size, outfd);
  6548. }
  6549.  
  6550. /* if we really write out a debug hunk, this fills in the remaining
  6551.  * spots, that are known only at the end of load-file output */
  6552.  
  6553. void
  6554. conditionally_rewrite_headers ()
  6555. {
  6556.   long size_of_debug_hunk,
  6557.        end_hunk = 0x3f2,
  6558.        eof;
  6559.  
  6560.   /* if we don't want a debug hunk, just return */
  6561.   if (number_of_debug_hunk == -1)  return;
  6562.  
  6563.   /* while we're at it, since we started the debug-hunk, lets finish it
  6564.    * now. */
  6565.   eof = lseek(outdesc, 0L, 2);
  6566.   dh.strs = eof - offset_of_debug_hunk - sizeof(dh) - dh.syms;
  6567.   /* just to be sure, we HAVE to pad to a long-boundery */
  6568.   if (eof & 3)
  6569.     {
  6570.       long zero = 0;
  6571.  
  6572.       mywrite(&zero, 4 - (eof & 3), 1, outdesc);
  6573.       eof = (eof + 3) & ~3;
  6574.     }
  6575.  
  6576.   mywrite(&end_hunk, sizeof(long), 1, outdesc);
  6577.  
  6578.   /* ok, so calculate the size of the debug hunk. This is the 
  6579.    * size of the debug_header plus the symbol and string tables,
  6580.    * but it doesn't include the 2 longs, that identify the hunk and
  6581.    * its length, whence the "- 2*sizeof(long)" */
  6582.   size_of_debug_hunk = eof - offset_of_debug_hunk - 2*sizeof(long);
  6583.   /* we actually need the size in longs.. */
  6584.   size_of_debug_hunk = LONGSIZE(size_of_debug_hunk);
  6585.  
  6586.   /* now first patch the debug-hunk itself, afterwards the load-file header */
  6587.   lseek(outdesc, offset_of_debug_hunk, 0);
  6588.   dh.len = size_of_debug_hunk;
  6589.   mywrite(&dh, sizeof dh, 1, outdesc);
  6590.  
  6591.   /* now the main header, this involves calculating, at which offset we
  6592.    * find the index for the debug hunk */   
  6593.   lseek(outdesc, (5 + number_of_debug_hunk)*sizeof(long), 0);
  6594.   mywrite(&size_of_debug_hunk, sizeof(long), 1, outdesc);
  6595.   lseek(outdesc, 0L, 2);
  6596.   /* that's it! */
  6597. }
  6598.  
  6599. /* this is the only information that we can store in a regular amiga
  6600.  * symbol, just its value, nothing further, that's why I added the 
  6601.  * debug-hunk-feature */
  6602.  
  6603. typedef struct {
  6604.   char *sym_name;
  6605.   long  sym_offset;
  6606. } simple_symbol;
  6607.  
  6608. /* we'll only define symbols after at most 3 hunks, ie. the code, data
  6609.  * and bss hunk, but not after the debug hunk, whence the index 3 */
  6610.  
  6611. simple_symbol *hunk_sym_tab[3];
  6612. int hunk_sym_tab_size[3], hunk_sym_tab_index[3];
  6613.  
  6614. void
  6615. init_symbol_hunks()
  6616. {
  6617.   int i;
  6618.  
  6619.   if (trace_files) fprintf(stderr, "init_symbol_hunks()\n");
  6620.  
  6621.   for (i = 0; i < 3; i++)
  6622.     {
  6623.        hunk_sym_tab[i] = 
  6624.          (simple_symbol *) xmalloc((hunk_sym_tab_size[i] = 10) * 
  6625.        sizeof(simple_symbol));
  6626.        hunk_sym_tab_index[i] = 0;
  6627.     }
  6628. }
  6629.  
  6630. /* this should go into libc, well, it wasn't there, so... */
  6631.  
  6632. char *
  6633. strsave(str)
  6634.     char *str;
  6635. {
  6636.   char *cp;
  6637.   int len = strlen(str);
  6638.   if (len)
  6639.     {
  6640.       cp = xmalloc(len+1);
  6641.       strcpy(cp, str);
  6642.     }
  6643.   else
  6644.     cp = NULL;
  6645.   return cp;
  6646. }
  6647.  
  6648. void
  6649. add_to_symbol_hunk(hunk_num, name, offset)
  6650.     int hunk_num;
  6651.     char *name;
  6652.     long offset;
  6653. {
  6654.    if (hunk_num == -1) return;
  6655.    if (hunk_num >= 3) fatal ("invalid hunk_number: %d\n", hunk_num);
  6656.  
  6657.    /* no checks for duplicate symbols. Since it is legitimate to have
  6658.     * symbols with the same name, we can't strip them.. just make 
  6659.     * sure not to call this function multiple times with the same
  6660.     * symbol, since it won't be detected, and you'll get several
  6661.     * labels for the same offset...
  6662.     */
  6663.     
  6664.    if (trace_files) fprintf(stderr, "add_to_symbol_hunk(%d, %s, %d)\n",
  6665.                 hunk_num, name, offset);
  6666.  
  6667.    hunk_sym_tab[hunk_num][hunk_sym_tab_index[hunk_num]].sym_offset = offset;
  6668.    hunk_sym_tab[hunk_num][hunk_sym_tab_index[hunk_num]++].sym_name = 
  6669.      strsave(name);
  6670.  
  6671.    if (hunk_sym_tab_index[hunk_num] == hunk_sym_tab_size[hunk_num])
  6672.     hunk_sym_tab[hunk_num] = (simple_symbol *)
  6673.       xrealloc(hunk_sym_tab[hunk_num],
  6674.             (hunk_sym_tab_size[hunk_num] <<= 1) * 
  6675.               sizeof(simple_symbol));
  6676. }
  6677.  
  6678. int
  6679. compare_simple_symbols(l1, l2)
  6680.     simple_symbol *l1, *l2;
  6681. {
  6682.   return l1->sym_offset - l2->sym_offset;
  6683. }
  6684.  
  6685. /* this writes the symbol subhunk #hunk_num, you call this just after
  6686.  * you created your {code,data,bss}-hunk */
  6687.  
  6688. void
  6689. write_symbol_hunk(hunk_num)
  6690.     int hunk_num;
  6691. {
  6692.   int i, j;
  6693.   simple_symbol *tab;
  6694.   long size, index;
  6695.  
  6696.   if (hunk_num == -1) return;
  6697.   if (hunk_num >= 3) fatal ("invalid hunk_number: %d\n", hunk_num);
  6698.   
  6699.   tab   = hunk_sym_tab[hunk_num];
  6700.   size  = hunk_sym_tab_size[hunk_num];
  6701.   index = hunk_sym_tab_index[hunk_num];
  6702.    
  6703.   /* kind of abused as general debug-flag:-) */
  6704.   if (trace_files) fprintf(stderr, 
  6705.                 "wsh: hnum=%d,size=%d,index=%d\n",
  6706.                hunk_num,size,index);
  6707.    
  6708.   if (index > 0)
  6709.     {
  6710.       qsort(tab, index, sizeof(simple_symbol), compare_simple_symbols);
  6711.  
  6712.       j = 0x3f0; /* HUNK_SYMBOL */
  6713.       mywrite(&j, 1, sizeof(long), outdesc);
  6714.    
  6715.       for (i = 0; i < index; i++)
  6716.         {
  6717.        register simple_symbol *ss = tab+i;
  6718.  
  6719.        j = LONGSIZE(strlen(ss->sym_name));
  6720.        mywrite(&j, 1, sizeof(long), outdesc);
  6721.  
  6722.        /* this will put garbage into unused bytes, but since all
  6723.         * known processors of this symbol-hunk will ignore the padding,
  6724.         * I'll leave this that way, until somebody finds a tool
  6725.         * that coughs on junk after the trailing zero-byte 
  6726.         * (perhaps some BCPL-"utility".. shudder... ) */
  6727.        mywrite(ss->sym_name, 1, 4*j, outdesc);
  6728.  
  6729.        mywrite(&(ss->sym_offset), 1, sizeof(long), outdesc);
  6730.     }
  6731.  
  6732.       j = 0;
  6733.       mywrite(&j, 1, sizeof(long), outdesc);
  6734.     }
  6735. }
  6736.  
  6737. /* now follow the quite similar routines for dealing with
  6738.  * reloc-subhunks, the difference to the symbol-subhunks is, that reloc
  6739.  * subhunks can be output only after the {code,data}-Hunks, AND there
  6740.  * can be more than one after each of them */
  6741.  
  6742. long *hunk_rel_tab[3], hunk_rel_tab_size[3], hunk_rel_tab_index[3];
  6743.  
  6744. void
  6745. init_reloc_hunk()
  6746. {
  6747.   int i;
  6748.  
  6749.   if (trace_files) fprintf(stderr, "init_reloc_hunk()\n");
  6750.  
  6751.   for (i = 0; i < 3; i++)
  6752.     {
  6753.        hunk_rel_tab[i] = 
  6754.          (long *) xmalloc((hunk_rel_tab_size[i] = 10) * sizeof(long));
  6755.        hunk_rel_tab_index[i] = 0;
  6756.     }
  6757. }
  6758.  
  6759. void
  6760. add_to_reloc_hunk(hunk_num, offset)
  6761.     int hunk_num;
  6762.     long offset;
  6763. {
  6764.    /* no checks for duplicate symbols, they will show up when we sort
  6765.     * the table, and we will strip them off before writing out the table */
  6766.  
  6767.    if (trace_files) fprintf(stderr, "add_to_reloc_hunk(%d, %d)\n", hunk_num, offset);
  6768.  
  6769.    hunk_rel_tab[hunk_num][hunk_rel_tab_index[hunk_num]++] = offset;
  6770.  
  6771.    if (hunk_rel_tab_index[hunk_num] == hunk_rel_tab_size[hunk_num])
  6772.     hunk_rel_tab[hunk_num] = (long *)
  6773.       xrealloc(hunk_rel_tab[hunk_num],
  6774.                    (hunk_rel_tab_size[hunk_num] <<= 1) * sizeof(long));
  6775. }
  6776.  
  6777. int
  6778. compare_longs(l1, l2)
  6779.     long *l1, *l2;
  6780. {
  6781.   return *l1 - *l2;
  6782. }
  6783.  
  6784. void
  6785. write_reloc_hunk()
  6786. {
  6787.    int i, j;
  6788.    long *tab, size, index;
  6789.    /* only write a hunk-header & -end, if we really output some relocs */
  6790.    int did_start_hunk = 0;
  6791.  
  6792.    for (i = 0; i < 3; i++)
  6793.      {
  6794.     tab   = hunk_rel_tab[i];
  6795.     size  = hunk_rel_tab_size[i];
  6796.     index = hunk_rel_tab_index[i];
  6797.  
  6798.     /* kind of abused as general debug-flag:-) */
  6799.         if (trace_files) fprintf(stderr, 
  6800.                  "wrh: i=%d,size=%d,index=%d\n",
  6801.                  i,size,index);
  6802.  
  6803.         if (index > 0)
  6804.       {
  6805.         qsort(tab, index, sizeof(long), compare_longs);
  6806.  
  6807.         /* kick out duplicate symbols.. I don't know, what
  6808.          * the loader would do, if it had to relocate the same
  6809.          * address twice.. BTW: can this happen or can't it???? */
  6810.         for (j = 0; j < index-1; )
  6811.           {
  6812.         if (tab[j] == tab[j+1])
  6813.           bcopy(tab+j+1, tab+j, ((index--)-j-1)*sizeof(long));
  6814.         else
  6815.           j++;
  6816.           }
  6817.  
  6818.         if (!did_start_hunk++)
  6819.           {
  6820.         j = 0x3ec; /* HUNK_RELOC32 */
  6821.         mywrite(&j, 1, sizeof(long), outdesc);
  6822.           }
  6823.  
  6824.         mywrite(&index, 1, sizeof(long), outdesc);
  6825.         mywrite(&i, 1, sizeof(long), outdesc);
  6826.         mywrite(tab, 1, index*sizeof(long), outdesc);
  6827.         hunk_rel_tab_index[i] = index;
  6828.       }
  6829.      }
  6830.    if (did_start_hunk)
  6831.      {
  6832.     j = 0;
  6833.        mywrite(&j, 1, sizeof(long), outdesc);
  6834.      }
  6835. }
  6836.  
  6837.  
  6838. void
  6839. write_datadata_relocs ()
  6840. {
  6841.   int numdd, i, prev;
  6842.  
  6843.   prev = lseek (outdesc, 0, SEEK_CUR);
  6844.   lseek (outdesc, datadata_relocs_offset, L_SET);
  6845.   
  6846.   numdd = hunk_rel_tab_index[number_of_data_hunk];
  6847.   if (numdd > numdatadata_relocs)
  6848.     fatal ("found more data-data relocs than estimated!\n", 0);
  6849.   
  6850.   mywrite (&numdd, 1, sizeof (long), outdesc);
  6851.   if (numdd)
  6852.     mywrite (hunk_rel_tab[number_of_data_hunk], numdd, sizeof (long), outdesc);
  6853.  
  6854.   lseek (outdesc, prev, L_SET);
  6855. }
  6856.  
  6857.  
  6858. /* create the bss hunk if needed */
  6859.  
  6860. void
  6861. write_bss()
  6862. {
  6863.   long bss_hunk[2];
  6864.   if (!databss_together && bss_size)
  6865.    {
  6866.      bss_hunk[0] = 0x3eb;
  6867.      bss_hunk[1] = LONGSIZE(bss_size);
  6868.      mywrite(bss_hunk, 1, sizeof bss_hunk, outdesc);
  6869.      write_symbol_hunk(number_of_bss_hunk);
  6870.      bss_hunk[0] = 0x3f2; /* HUNK_END */
  6871.      mywrite(bss_hunk, 1, sizeof(long), outdesc);
  6872.    }
  6873. }
  6874.  
  6875. /* this scans one object file for its symbols, and deposits them in 
  6876.  * the symbol-hunk tables for later output */
  6877.  
  6878. void
  6879. look_for_file_syms (entry)
  6880.      struct file_entry *entry;
  6881. {
  6882.   register struct nlist *p = entry->symbols;
  6883.   register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
  6884.  
  6885. #if 0
  6886.   /* don't do this, it only confuses most amiga disassemblers.. */
  6887.  
  6888.   /* Generate a local symbol for the start of this file's text.  */
  6889.  
  6890.   if (discard_locals != DISCARD_ALL)
  6891.     add_to_symbol_hunk(number_of_code_hunk, entry->local_sym_name, 
  6892.        entry->text_start_address);
  6893. #endif
  6894.  
  6895.   /* Read the file's string table.  */
  6896.  
  6897.   entry->strings = (char *) alloca (entry->strs_size);
  6898.   read_entry_strings (file_open (entry), entry);
  6899.  
  6900.   for (; p < end; p++)
  6901.     {
  6902.       register unsigned char type = p->n_type;
  6903.       register int write = 0;
  6904.       int this_hunk;
  6905.       char *cp;
  6906.  
  6907.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  6908.  
  6909.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  6910.                 /* types of symbols are never written */
  6911.                 /* globally, though they are stored */
  6912.                 /* globally.  */
  6913.         write = output_style == OUTPUT_RELOCATABLE;
  6914.       else if (!(type & (N_STAB | N_EXT)))
  6915.           /* ordinary local symbol */
  6916.       write = ((discard_locals != DISCARD_ALL)
  6917.            && !(discard_locals == DISCARD_L &&
  6918.                (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  6919.            && type != N_WARNING);
  6920.  
  6921.       else if (!(type & N_EXT))
  6922.     /* debugger symbol */
  6923.         write = (strip_symbols == STRIP_NONE);
  6924.  
  6925.       /* skip STAB symbols if present */
  6926.       write = write && !(type & N_STAB);
  6927.  
  6928.       /* those weird types are NOT output in the normal symbols:-)) */
  6929.       write = write && (type != N_ABS && type != (N_ABS|N_EXT));
  6930.  
  6931.       /* don't know where those symbols come from, they're well suited to
  6932.        * crash enforcer, and they're not `real' symbols anyway.. */
  6933.       if (p->n_un.n_strx > entry->strs_size) continue;
  6934.  
  6935.       /* symbols that end with a dot are only useful for gdb, 
  6936.        * not for a normal amiga debugger (currently gcc_compiled. and
  6937.        * gcc_compiled2.) so skip them in this section */
  6938.  
  6939.       /* check to see, whether this string ends with a dot */
  6940.       if (write && p->n_un.n_strx)
  6941.         {
  6942.           cp = rindex (p->n_un.n_strx + entry->strings, '.');
  6943.  
  6944.       write = write && !(cp && !cp[1]);
  6945.       
  6946. #if 0
  6947.       printf ("%s >%s<\n", write ? "adding" : "skipping", p->n_un.n_strx + entry->strings);
  6948. #endif
  6949.     }
  6950.  
  6951.       if (write)
  6952.     {
  6953.       if (p->n_un.n_strx)
  6954.         {
  6955.           switch (type & ~N_EXT)
  6956.             {
  6957.           case N_TEXT:
  6958.             this_hunk = number_of_code_hunk;
  6959.             break;
  6960.           case N_SETV:
  6961.           case N_DATA:
  6962.             this_hunk = number_of_data_hunk;
  6963.             break;
  6964.           case N_UNDF:
  6965.           case N_BSS:
  6966.             this_hunk = number_of_bss_hunk;
  6967.             break;
  6968.           default:
  6969.             error ("unknown type %d while trying to build lsymhunk", type);
  6970.             goto skip1;
  6971.             }
  6972.  
  6973.           add_to_symbol_hunk(this_hunk, p->n_un.n_strx + entry->strings,
  6974.                  p->n_value);
  6975. skip1:    ;
  6976.             }
  6977.     }
  6978.     }
  6979. }
  6980.  
  6981. /* scan all input files for symbols and store them in the symbolhunk tables */
  6982.  
  6983. void
  6984. look_for_symbols()
  6985. {
  6986.   int this_hunk;
  6987.   int i;
  6988.   symbol *sp;
  6989.  
  6990.   if (strip_symbols == STRIP_ALL)
  6991.     return;
  6992.  
  6993.   /* Write the local symbols defined by the various files.  */
  6994.  
  6995.   each_file (look_for_file_syms, 0);
  6996.   file_close ();
  6997.  
  6998.   /* Scan the symbol hash table, bucket by bucket.  */
  6999.  
  7000.   for (i = 0; i < TABSIZE; i++)
  7001.     for (sp = symtab[i]; sp; sp = sp->link)
  7002.       {
  7003.     struct nlist nl;
  7004.  
  7005.     /* Compute a `struct nlist' for the symbol.  */
  7006.  
  7007.     nl.n_value = 0;
  7008.  
  7009.     if (sp->defined || sp->referenced)
  7010.       {
  7011.         /* common condition needs to be before undefined condition */
  7012.         /* because unallocated commons are set undefined in */
  7013.         /* digest_symbols */
  7014.         if (sp->defined > 1) /* defined with known type */
  7015.           {
  7016.         /* If the target of an indirect symbol has been
  7017.            defined and we are outputting an executable,
  7018.            resolve the indirection; it's no longer needed */
  7019.         if (output_style != OUTPUT_RELOCATABLE
  7020.             && ((sp->defined & ~N_EXT) == N_INDR)
  7021.             && (((symbol *) sp->value)->defined > 1))
  7022.           {
  7023.             symbol *newsp = (symbol *) sp->value;
  7024.             nl.n_type = newsp->defined;
  7025.             nl.n_value = newsp->value;
  7026.           }
  7027.         else
  7028.           {
  7029.             nl.n_type = sp->defined;
  7030.             if (sp->defined != (N_INDR | N_EXT))
  7031.               nl.n_value = sp->value;
  7032.             else
  7033.               nl.n_value = 0;
  7034.           }
  7035.           }
  7036.         else if (sp->max_common_size) /* defined as common but not allocated. */
  7037.           {
  7038.         /* happens only with -r and not -d */
  7039.         /* write out a common definition */
  7040.         nl.n_type = N_UNDF | N_EXT;
  7041.         nl.n_value = sp->max_common_size;
  7042.           }
  7043.         else if (!sp->defined)          /* undefined -- legit only if -r */
  7044.           {
  7045.         nl.n_type = N_UNDF | N_EXT;
  7046.         nl.n_value = 0;
  7047.           }
  7048.         else
  7049.           fatal ("internal error: %s defined in mysterious way", sp->name);
  7050.  
  7051.         switch (nl.n_type & ~N_EXT)
  7052.           {
  7053.         case N_TEXT:
  7054.           this_hunk = number_of_code_hunk;
  7055.           break;
  7056.         case N_SETV:
  7057.         case N_DATA:
  7058.           this_hunk = number_of_data_hunk;
  7059.           break;
  7060.         case N_UNDF:
  7061.         case N_BSS:
  7062.           this_hunk = number_of_bss_hunk;
  7063.           break;
  7064.         case N_ABS:
  7065.           break;
  7066.         default:
  7067.           error ("unknown type %d while trying to build symhunk", nl.n_type);
  7068.           goto skip2;
  7069.           }
  7070.  
  7071.         /* sigh, there is no equivalent in the symbol section of a load
  7072.          * file on the amiga, have to forget about those symbols */
  7073.         if ((nl.n_type & ~N_EXT) == N_ABS)
  7074.           continue;
  7075.  
  7076.         add_to_symbol_hunk(this_hunk, sp->name, nl.n_value);
  7077. skip2:    ;
  7078.       }
  7079.       }
  7080. }
  7081.  
  7082. void
  7083. relocate_set_vectors (vectors, num_entries)
  7084.     unsigned long *vectors;
  7085.     int num_entries;
  7086. {
  7087.   unsigned long i;
  7088.   unsigned long offset = set_sect_start;
  7089.   int hunk_num;
  7090.  
  7091.   while (num_entries-- > 0)
  7092.     {
  7093.       /* the number of entries for this symbol */
  7094.       i = *vectors++; offset += 4;
  7095.       while (num_entries --, i--)
  7096.     {
  7097.       hunk_num = number_of_code_hunk;
  7098.       if (*vectors >= text_size)
  7099.         {
  7100.           if (*vectors >= text_size + data_size)
  7101.               {
  7102.           hunk_num = number_of_bss_hunk;
  7103.           if (databss_together)
  7104.             *vectors -= text_size;
  7105.           else
  7106.             *vectors -= text_size + data_size;
  7107.         }
  7108.           else
  7109.         {
  7110.           hunk_num = number_of_data_hunk;
  7111.           *vectors -= text_size;
  7112.         }
  7113.         }
  7114.       add_to_reloc_hunk (hunk_num, offset);
  7115.       ++vectors;
  7116.       offset += 4;
  7117.     }
  7118.       /* check.. HAS to be zero */
  7119.       if (*vectors)
  7120.     fatal ("set-vector corrupt, num_entries = %d", num_entries);
  7121.       vectors++; offset += 4; --num_entries;
  7122.     }
  7123. }
  7124. #endif
  7125.